Search code examples
javascriptregex

Remove hashtag symbol js, by regex


Tried to search on the forum but could not find anything that would precisely similar to what i need. Im basically trying to remove the # symbol from results that im receving, here is the dummy example of the regex.

let postText = 'this is a #test of #hashtags';
var regexp = new RegExp('#([^\\s])', 'g');
postText = postText.replace(regexp, '');

console.log(postText);

It gives the following result

this is a est of ashtags

What do i need to change around so that it removes just the hashtags without cutting the first letter of each word


Solution

  • You need a backreference $1 as the replacement:

    let postText = 'this is a #test of #hashtags';
    var regexp = /#(\S)/g;
    postText = postText.replace(regexp, '$1');
    console.log(postText);
    // Alternative with a lookahead:
    console.log('this is a #test of #hashtags'.replace(/#(?=\S)/g, ''));

    Note I suggest replacing the constructor notation with a regex literal notation to make the regex a bit more readable, and changing [^\s] with a shorter \S (any non-whitespace char).

    Here, /#(\S)/g matches multiple occurrences (due to g modifier) of # and any non-whitespace char right after it (while capturing it into Group 1) and String#replace will replace the found match with that latter char.

    Alternatively, to avoid using backreferences (also called placeholders) you may use a lookahead, as in .replace(/#(?=\S)/g, ''), where (?=\S) requires a non-whitespace char immediately to the right of the current location. If you need to remove # at the end of the string, too, replace (?=\S) with (?!\s) that will fail the match if the next char is a whitespace.