views:

50

answers:

3

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, '');
A: 

This?

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

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.

MartyIX
+2  A: 

Here ya go:

postText = 'this is a #test of #hashtags';
var regexp = new 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.

Ian Silber