Skip to content

Posts tagged ‘highlight’

24
Mar

Highlight words in text with jQuery

highlight words jqueryOn the right is an example of word-highlighting in a blog post, done with jQuery (my javascript library of choice).  I needed to highlight certain words in blocks of formatted text, so I went searching for an existing solution.  I found a pretty good starting point, posted by bjarlestam on Stackoverflow.  His highlighting function is below.  It wraps the word inside a span tag with a class of your choosing.

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>";
        });
    });
};

This is nice, because it uses a case-insensitive regular expression to find the word to highlight.  However, there is a flaw.  If you call this function on an element with non-text child elements, and the tag/attribute names or attribute values match the word to highlight, this function will mess up your HTML.  We’d like it to apply only to text nodes.
Read moreRead more