2

I have a program that is supposed to take key words and highlight/color them with CSS.

I'm using jQuery because I want to eventually alter which words are highlighted, all done by the user.

Right now the problem isn't that nothing is getting highlighted (yay), but instead that not everything is not getting highlighted (oh no). I have several words set up to go through and get highlighted (balloon, Dorothy, cyclone) but often what happens is that not all, if any, of certain words get colored.

Hopefully this jsFiddle thing helps explain it better than I can. You'll notice by the second line that the first word and keyword, Dorothy, isn't red like I would expect.

thanks. sorry if I'm too incoherent or anything, feedback is appreciated

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
enche
  • 220
  • 2
  • 7
  • Dorothy is red when i load your fiddle in chrome. Looks fine. – dezman Jul 18 '12 at 18:10
  • 1
    Here's a cleaner fiddle of the same problem: http://jsfiddle.net/Wexcode/c8N7t/ – Wex Jul 18 '12 at 18:12
  • 1
    You are replacing the html with the text, removing all previous formatting. Also, you are creating multiple spans with the same id, you should change that to classes – MrOBrian Jul 18 '12 at 18:16

1 Answers1

4

Is this what you want?

$(function(){
     var keyWord = new Array("Dorothy","cyclone","miles","house","balloon");
     var regexp = new RegExp(keyWord.join("|"),"g");
     $('#oz li').html( function(i,value){
          return value.replace(regexp ,
               '<span containsStringImLookingFor="true" id="$&">$&</span>');
     });
});

Explanation

regexp is /Dorothy|cyclone|miles|house|balloon/g regular expression,which matches all the listed words in your array. .replace() method replaces all the matched words by '<span containsStringImLookingFor="true" id="{matched word}">matched word</span>' template. '$&' in replace method indicates current matched word.

Engineer
  • 47,849
  • 12
  • 88
  • 91
  • 1
    whats the difference between $& and $1 ? – mkoryak Jul 18 '12 at 18:21
  • 2
    @mkoryak Read the [MDN](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter). Also for `$1` you need to use additional `()` brackets, likewise `.replace(/(Dorothy)/h,'$1')`,which are not needed with `$&` – Engineer Jul 18 '12 at 18:22
  • this seems to work great! as a newbie I'm gonna have to read up to understand what regexp is too. thank you very very much – enche Jul 19 '12 at 15:54