jQuery: searching and highlighting text

Searching and highlighting text is simple with jQuery. Here's a basic code for accomplishing this task:

function highlight () {

$('#search').submit(function() {
        var $query = $('#search #q').val();
        var re = new RegExp($query, 'g');
        var targetHtml = $('#text').html();

       if(re.test(targetHtml)) {
           var matches = targetHtml.match(re);
           $('#text').html(targetHtml.replace(re, '<span class="highlight">'+matches[0]+'</span>'));          
       } else {
           alert('Term not found.');
        return false;


$(document).ready(function() {



As you can see, I've used the RegExp object to turn user input into a regular expression. Then I performed a global search using the test() and match() methods of this object. You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.