Could a Javascript regex error be resolved with the addition of look-behind functionality?

Currently, I am working on an exercise within a Javascript learning platform.

The task is as follows:

  • Input: A string consisting of words, with some words possibly containing hashtags (prefixed with #).

  • Output: An array of strings that have been prefixed with a hashtag but do not contain the actual hashtag character.

  • It's important to note that single pound signs alone are not considered valid inputs (e.g., "#" would result in an empty array).

  • If a word has multiple leading hashtags, only the last one should be considered (e.g., "##example" would return ["example"])
  • Hashtags must not appear within the middle of a word (e.g., "in#line hashtag" should return an empty array)
  • Furthermore, hashtags must come before alphabetical characters (e.g., "#123abc" or "#?" are invalid inputs)

This was my attempt at solving the problem:

function getHashtags(post) {
  return /#(\w+)/.exec(post)
}

However, the output I'm receiving looks like this:

String Input: Hello #world
Outpu t: [ '#world', 'world', index: 6, input: 'Hello #world' ]

String Input: #lol #sorryNotSorry #heya #coolbeans
Output: [ '#lol','lol', index: 0, input: '#lol #sorryNotSorry #heya #coolbeans']

String Input: # # # #
Output: null

String Input: this is an in#line hash
Output: [ '#line', 'line', index: 13, input: 'this is an in#line hash' ]

String Input: too ##many tags
Output: [ '#many', 'many', index: 5, input: 'too ##many tags' ]

String Input: invalid chars #$? #;wha
Output: null

String Input: "" //empty string
null

String Input: #blue#red#yellow#green
Output:[ '#blue', 'blue', index: 0, input: '#blue#red#yellow#green' ]

I believe I may need to implement lookback functionality, although it's not directly supported in Javascript and I haven't found a suitable workaround yet. Can anyone offer any guidance?

Answer №1

It seems like you're on the right track with your approach. Using exec will give you the first set of results, and by continuing to call it with the global flag g, you can retrieve subsequent matches. The example provided here is sourced from mozilla's website:

var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
  var msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

Exec

I must commend you for presenting your question in a clear manner that demonstrates your attempts at solving the issue. Now, let me guide you through how you could implement this solution:

function getHashtags(post)
{
    regex = /#(\w+)/g;
    arr = [];

    while((results = regex.exec(post)) !== null)
    {
        arr.push(results[1]);
    }

    return arr;
}

Answer №2

Do not place hashtags in the middle of a word (e.g. "in#line hashtag" results in an empty array)

-- Use the non-word boundary code \B to prevent a word character from appearing right before the #. Additionally, to avoid matching when the # is within the hashtag, include a word boundary that is not followed by #: (?!#)\b.

Hashtags should come before alphabetical characters (e.g. "#120398" or "#?" are not valid)

-- Add [a-zA-Z] immediately after # and then utilize \w. If using /i modifier, use [a-z].

Therefore, use

/\B#+([a-z]\w*(?!#)\b)/gi

Check out the demo

This method caters to basic Latin-script based hashtag extraction.

function getHashtags(post) {
  var re = /\B#+([a-z]\w*(?!#)\b)/gi;
  arr = []; 
  while ((m = re.exec(post)) !== null) {
    arr.push(m[1]);
    document.write("Hashtag: " + m[0] + ", name: " + m[1] + "<br/>");
  }
  return arr;
}


var strs = ['##alot', 'Hello #world', '#lol #sorryNotSorry #heya #coolbeans', '# # # #', 'this is an in#line hash', 'too ##many tags', 'invalid chars #$? #;wha', '', '#blue#red#yellow#green'];
strs.forEach(function (str) {
  console.log(getHashtags(str));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the automated process for extracting objects from an array and assigning them to variables?

Is there a way to automatically assign objects from an array to variables based on their corresponding index? Here is what I attempted: response.forEach((el, i, )=>{ let nameProduct[i] = ` the name of product : ${response[i].nameProduct}`; conso ...

What is the best way to develop a JavaScript function that divides the total width by the number of table headers (`th`)?

I recently came across this amazing scrollable table on a website, but I'm facing an issue with resizing the headers equally. Due to my lack of knowledge in JavaScript, I'm uncertain about how to tackle this problem. My intuition tells me that a ...

Activate the button solely when the text field has been populated without any spaces

Searching for a solution to my query, but all the suggestions I've encountered don't consider spaces as valid input. In the join function I have, the button should be disabled if the user enters only spaces. A requirement is for actual text inpu ...

The DiscordAPIError occurred due to the incorrect placement of required options in the form body. In order to resolve this issue, ensure that required

Hey everyone! So, I've been trying to solve an issue I encountered after posting my initial question without receiving any answers. I've searched extensively online, formatted the code, but unfortunately, I still haven't been able to find a ...

Using Node JS to pass variables to the client

Currently, I am utilizing Node JS and Express for my server-side needs. In my server-side code, I pass a variable (sources) to my EJS template. Part of this variable is used to populate a list on the webpage. However, when a user clicks on an item in the ...

Retrieve the properties of an object

I have a JavaScript program where I retrieve values from a JSON file and store them in an array. However, when I attempt to access the elements of this array, it returns nothing. Below is the function that pushes temperatures: temperatures = [] get_info ...

Implementing event listeners with Angular UI-Router

Currently, I am working with Angular 1.4.5 and Angular Ui Router. I am facing an issue where I am trying to utilize addEventListener to execute a function when a text field is blurred. The challenge I am encountering is that during the load state, the elem ...

I am facing an issue with my Java program as it is unable to import a text file

import java.util.Scanner; class RacecarInfo { int carID, trackLength; String raceTrack; double raceTime; } public class App { public static void main(String[] args) throws Exception { Scanner fileInput = new Scanner(new j ...

Navigating currency in JavaScript

I'm considering whether this is the best approach for handling currency in JavaScript. The idea is to restrict the user to entering only numbers and a decimal point in the input field. This code is a combination of answers I found on this website and ...

Employing Isotope/jQuery for organizing posts on Tumblr in columns with the ability to infinitely scroll

Alright so, here we have the classic dilemma where scripts are running before images load. And to make matters more complicated, on Tumblr, there's no way to access image dimensions before they're loaded into the DOM... $('#thumbnails&apos ...

Tips on sorting a struct array with qsort

Tasked with the challenge of retrieving a binary file, reading it into an array comprised of structs and sorting it based on a specific array within each struct has proven to be quite the hurdle. At this moment in time, my main struggle lies within the rea ...

A guide on customizing ng-map markers by assigning colors to different categories

One of the functionalities I have allows users to see nearby locations based on their position and selected radius. These locations fall into different categories, and now I want to customize the markers' colors based on those categories. Here is a s ...

MongoDb Mongoose's aggregatePagination feature occasionally displays duplicated documents across various pages

Currently, I am encountering an issue related to pagination in mongodb and mongoose. My goal is to search through a group of Tutors based on certain criteria and have the results paginated and sorted by their updated date. However, the problem arises when ...

What is the best way to handle variables in javascript?

After making an AJAX request, I expected the results to display when I select from the drop down menu. However, I encountered a problem where only a table is being displayed. I am confused as to why the data is not coming from the variables $grade (calcula ...

Get the matching value of `:` from the function to access elements in the array

Dealing with a large array and a function that returns index lists into the array presents some challenges. Here is an example: import numpy n = 500 a = numpy.random.rand(n) def get_idx(k): # More complex in practice return range(n) if k > ...

Struggling to eliminate the scrollbar on a Material UI Dialog

I have a modal window that includes a keyboard, but I'm encountering some issues. Despite adding overflow:'hidden' as inline CSS, the scrollbar refuses to disappear. Furthermore, even when utilizing container-full padding-0 in Bootstrap, th ...

Trouble retrieving data from cross-domain JSON request in AngularJS

Struggling all day to retrieve the JSON data from this specific URL: As a beginner in cross-domain calls, I attempted using JSONP and $get.JSON methods without any luck. My main goal is to extract the information from that URL link and store it in an Angu ...

What is the best approach for parsing JSON data and dynamically populating multiple attributes or inner HTML elements?

Let's consider a scenario where we have a program sending an ajax request to a PHP file, and this program needs to utilize the response values for tasks like: Updating form inputs Setting checkboxes Updating the innerHTML of elements The code below ...

By introducing the directive, the binding functionality becomes ineffective

Just starting out with Angular and working on a mobile app using angularjs and the ionic framework. I have an input field for project name that includes a directive to check if the name already exists, disabling data binding if it does. Any guidance would ...

How can I resize an element using jQuery resizable and then revert it back to its original size with a button click?

I need help figuring out how to revert an element back to its original size after it has been modified with .resizable. I attempted the following: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="//code. ...