here is my code:
var keys = keyword.split(' ');
//alert(keys);
for(var i=0; i<keys.length; i++)
{
var re = new RegExp(keys[i], "gi");
var NewString = oldvar.replace(re, '<span style="background-color:#FFFF00">'+keys[i]+'</span>');
document.getElementById("wordlist").innerHTML=NewString;
alert(keys[i]);
}
but here if I put a string “a b”; its split into two letters “a” and “b”
and this replace function replace “a” but when it get “b” it overwrite and only replace “b”.
but I want to highlight both “a” and “b”.
how to solve this?
I got another problem . If I replace/highlight it then it replace all “a” and “b” of HTML tag. so, how to prevent to replace those html tag. but also when I display the whole text I need all html tag
You can actually do a single regex replace like this:
Example – http://jsfiddle.net/zEXrq/1/
What it is doing is merging all keys into a single regex seperated by
|which will match all the words then running the replacer function on the matches.Example 2 – http://jsfiddle.net/zEXrq/2/