jQuery: highlight words on titles

by gabrieleromanato

HTML

<h1>WordPress and lorem ipsum dolor</h1>
<h2>Lorem ipsum dolor with CSS and JavaScript</h2>
<h1>Ad ipsum valet but jQuery</h1>

CSS

body {
    margin: 2em auto;
    width: 100%;
    max-width: 40em;
    font: 85% Arial, sans-serif;
}

h1, h2 {
    font-weight: normal;
    margin: 0.5em 0;
}

JavaScript

(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);


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


});