Lets say you have a page with searchresults base on the search term ‘foo’ and you want to highlight all appearances of that word in the results list html. Well, a simple replace function won’t work, because it will not take into account that some appearances of the word might be in uppercase of partially in uppercase. Also, using a /term/gi will not work because you would replace the uppercased word with the original term, which might be is in lowercase. So, this is the solution:
var html = '<ul><li>These are the foo fighters</li>';
html+='<li>Foo fighters are the best</li></ul>';
var term = 'foo';
var re = new RegExp('(' + term + ')', 'gi');
html = html.replace(re, '<span class="highlighted">$1</span>');
Obviously you can set any formatting on the highlighted class to make it appear the way you want in the browser.
