This answer works almost perfectly for my needs. The problem is that it will also match URL values in the href attribute of an a tag. So If I have:
<a href="/a-link-to-a-porsche-page">This is a link to a porsche page</a>
and use this selector:
$("a").highlight("porsche", "highlighted");
porsche gets matched in both the url and the link text. What can be done so that values of the href attribute are omitted?
Previously referenced answer for posterity:
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp(str, "gi");
return this.each(function () {
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
});
};
Didn't know about jsfiddle. Here's a more complete example based on justkt's response: http://jsfiddle.net/Dzejms/L5Knh/1/