Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top