2
    function highlight(container,what) {
    var content = container.innerHTML,
        pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'),
        replaceWith = '$1<span style="background-color:red">$2</span>$3',
        highlighted = content.replace(pattern,replaceWith);
    return (container.innerHTML = highlighted) !== content;
 }

Above is the function written to highlight a specific word in the whole web page.

I am using it is

 highlight(document.body,"the");

And it works. If it is found any word, it makes it red background. The problem now is, once I run the functions, the javascript stops working on web pages.

Can someone help me to sort the problem. My guess is that the regex have issues. I am new to regex.

Thanks for any help.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307

0 Answers0