Hashtag strip from string using JavaScript

I have a line that may contain Twitter hashtags. I would like to remove it from the string. How can I do it? I am trying to use the RegExp class, but it does not work. What am I doing wrong?

This is my code:

var regexp = new RegExp('\b#\w\w+'); postText = postText.replace(regexp, ''); 
+7
javascript twitter
source share
3 answers

Here ya go:

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

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

+10
source share

You can write:

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

I do not see resonance for the first \w . The + sign is used for one or more cases. (Or are you only interested in hashtags with two characters?)

g allows "global" matching. When using the replace () method, specify this modifier to replace all matches, not just the first one.

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

Hope this helps.

+6
source share

It?

 <script> postText = "this is a #bla and a #bla plus#bla" var regexp = /\#\w\w+\s?/g postText = postText.replace(regexp, ''); alert(postText) </script> 
+1
source share

All Articles