Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

var hashtags = new Array("home","car", "tree");

tw.text.replace('#home', '<span class="hash">#home</span>')

How would I do that?

Thank you in advance.

share|improve this question

2 Answers 2

up vote 4 down vote accepted
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 which could lead to duplicate replacement.

share|improve this answer
    
Perfect, thank you, is there also a simple way to check for the "uppercase" version of the words as well? Like HOME, CAR, TREE? –  matt Mar 10 '13 at 18:29
    
I think you could use new RegExp('#' + elem, 'i') and then .replace(regexp, '<span...>#\0</span>') –  Explosion Pills Mar 10 '13 at 18:31

I would build a regex to do the 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 up being #(thing|another|etc...) so all replacements are done in one pass.

share|improve this answer
    
Thank you, see my comment on the other answer. In a rex the check for the pure uppercase version should be easier i guess. However I have no idea how to? –  matt Mar 10 '13 at 18:31
    
Thank you, it's i –  matt Mar 10 '13 at 18:36
    
well, the i switch makes the regex case insensitive, meaning it matches HoMe and home and HOME. You would add the flag to the second parameter, which already sets the g for global flag, when building the regex... new RegExp('...','gi') –  Billy Moon Mar 10 '13 at 18:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.