Javascript: Text Replace for multiple lines in an array?

I have an array with Twitter hashtags. And I want to filter the tw.text string for these hashtags and wrap the words in span

 var hashtags = new Array("home","car", "tree"); tw.text.replace('#home', '<span class="hash">#home</span>') 

How can I do it?

Thanks in advance.

+6
source share
2 answers
 hashtags.forEach(function (elem) { tw.text = tw.text.replace('#' + elem, '<span class="hash">#' + elem + "</span>"); }); 

This does not account for tags that contain other tags that could lead to duplicate replacements.

+4
source

I would build a regex to do replacements like this:

 var hashtags = new Array("home","car", "tree"); var rex = new RegExp("#("+hashtags.join("|")+")",'g') tw.text.replace(rex, '<span class="$1">#$1</span>') 

Regex ends with #(thing|another|etc...) , so all replacements are done in one go.

+3
source

All Articles