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, '');
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.
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.
This?
postText = "this is a #bla and a #bla plus#bla"
var regexp = /\#\w\w+\s?/g
postText = postText.replace(regexp, '');
console.log(postText)
精彩评论