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

3
  • Dorothy is red when i load your fiddle in chrome. Looks fine. Commented Jul 18, 2012 at 18:10
  • 1
    Here's a cleaner fiddle of the same problem: jsfiddle.net/Wexcode/c8N7t Commented Jul 18, 2012 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 Commented Jul 18, 2012 at 18:16

1 Answer 1

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.

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

3 Comments

whats the difference between $& and $1 ?
@mkoryak Read the MDN. Also for $1 you need to use additional () brackets, likewise .replace(/(Dorothy)/h,'$1'),which are not needed with $&
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

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.