jQuery: highlight words on titles

jQuery: highlight words on titles

How to highlight words on headings with jQuery.

If you use WordPress or another CMS, you will probably try someday to highlight a couple of keywords on your blog titles. This comes particularly handy when you want to display your search results or some featured posts. jQuery will do all the heavy-lifting for you.

Obviously we need a small plugin that takes one or more words and replace all the occurrences of such words in the text with an HTML element. The best way to accomplish this task is to use a comma-separated list of words as a plugin option.

This list will be later turned into a regular expression by means of the RegExp constructor:


(function($) {
    $.fn.highlightTitle = function(options) {
        var that = this;
        if (!that.is(':header')) {
            return;
        }
        options = $.extend({
            words: '',
            color: 'yellow'
        }, options);
        var parts = options.words.split(',');
        var str = parts.join('|');
        return this.each(function() {
            var html = $(this).html();
            $(this).html(html.replace(new RegExp('(' + str + ')', 'gi'), '<span style="background:' + options.color + ';">$1</span>'));
        });
    };
})(jQuery);

We've used the | character which has a special meaning in regular expressions: it simply marks an alternative to the current pattern. So if our words are tea,blue,sun our regular expression will match one or more of these words if the pattern matches the current title's text.

An example:


$(function() {
    $('h1, h2').highlightTitle({
        words: 'css,wordpress,jquery,javascript'
    });
});

You can see the demo on this page.