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.

matt
  • 42,713
  • 103
  • 264
  • 397

2 Answers2

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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 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, '#\0')` – Explosion Pills Mar 10 '13 at 18:31
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.

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • 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
  • 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