'Strip hashtags from string using JavaScript

I have a string that may contains Twitter hashtags. I'd like to strip it from the string. How should I do this? I'm trying to use the RegExp class but it doesn't seem to work. What am I doing wrong?

This is my code:

var regexp = new RegExp('\b#\w\w+');
postText = postText.replace(regexp, '');


Solution 1:[1]

Here ya go:

postText = 'this is a #test of #hashtags';
var regexp = /#\S+/g;
postText = postText.replace(regexp, 'REPLACED');

This uses the 'g' attribute which means 'find ALL matches', instead of stopping at the first occurrence.

Solution 2:[2]

You can write:

// g denotes that ALL hashags will be replaced in postText    
postText = postText.replace(/\b\#\w+/g, ''); 

I don't see a reson for the first \w. The + sign is used for one or more occurences. (Or are you interested only in hashtags with two characters?)

g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.

Source: http://www.regular-expressions.info/javascript.html

Hope it helps.

Solution 3:[3]

This?

postText = "this is a #bla and a #bla plus#bla"
var regexp = /\#\w\w+\s?/g
postText = postText.replace(regexp, '');
console.log(postText)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew
Solution 2
Solution 3