6

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.

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thank you, is there also a simple way to check for the "uppercase" version of the words as well? Like HOME, CAR, TREE?
I think you could use new RegExp('#' + elem, 'i') and then .replace(regexp, '<span...>#\0</span>')
3

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.

2 Comments

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?
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')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.