jQuery to Search and Highlight Matching Text

Highlight text in html page

How to highlight text in HTML with JavaScript or jQuery code.

You may also read Convert string to lowercase using JavaScript

Let me explain the basic logic first. The idea is to look into the browser object’s content and try to match the word or phrase using the regular expression. Then, the object is replaced with the highlighted CSS, if the search matches.

First, jQuery highlights text code, and later the explanation…

jquery select and highlight text

function replaceText() {

    $("body").find(".highlight").removeClass("highlight");

    var searchword = $("#searchtxt").val();

    var custfilter = new RegExp(searchword, "ig");
    var repstr = "<span class='highlight'>" + searchword + "</span>";

    if (searchword != "") {
        $('body').each(function() {
            $(this).html($(this).html().replace(custfilter, repstr));
        })
    }
}
  1. $("body").find(".highlight").removeClass("highlight");
    This line removes the previously highlighted searched words.
  2. var custfilter = new RegExp(searchword, "ig");
    “i” is used to ignore cases and “g” is used to search patterns throughout the string. Look at this Javascript regular expression link for more info. (of course, you can use more complex pattern matches).
  3. $(“body”).each(function( ) {…});
    I am looking for the search word throughout the ‘body’ element, hence, for each word in the element, I am comparing the lookup text. If you want to search for particular content or block of content, then use the element ID, for example, $(“#division”).each(function(){});
  4. $(this).html($(this).html().replace(custfilter, repstr));
    $(this) here refers to the ‘body’ element, using java script’s “replace”  function we are replacing the searched word with the filtered word, with little CSS to highlight it!

DEMO

CSS

.highlight{ 
  background:#00FF00; 
  padding:1px; 
  border:#00CC00 dotted 1px; 
}

Content

<body>
  <input type="text" id="searchtxt" />
  <input type="button" value="search" onClick="replaceText();" id="highlightButton" />
  <p>
    The ACM Digital Library, a part of the ACM Portal, contains a comprehensive archive of the organization's journals, magazines, and conference proceedings. Online services include a forum called Ubiquity and Tech News digest.
    
    ACM requires the copyright of all submissions to be assigned to the organization as a condition of publishing the work.[2] Authors may post the documents on their own websites, but they are required to link back to the digital library's reference page for the paper. Though authors are not allowed to charge for access to copies of their work, downloading a copy from the ACM site requires a paid subscription.
  </p> 
 </body>

Just added a text box and a button; onclick of which search is triggered!

Shares

Recommended Articles

8 Comments

  1. This code doesn’t apply the CSS anywhere, it just replaces all results with a lowercase version of the same words.
    It also has a syntax error.

    1. Hi X, thanks for your comment. Can you let us know which browser you are using and version? We will have a look and possibly update the code.

  2. This post does not work.You should first test this before posting. Or post a working demo

    1. Hi doorgo, Thanks for the comment. I will look into it. Can you please let me know which browser you are trying this and version of it?

  3. The only thing this doesn’t solve is removing the span that gets added, which didn’t matter in my case since resetting the search blows away the html and recreates it.

    function replaceText(searchword) {
    $(“body”).find(“.highlight”).removeClass(“highlight”);

    if (searchword != “”) {
    $(‘body’).each(function () {
    var r = $(this).html().replace(new RegExp(searchword, “ig”), function (match) {
    return “” + match + “”;
    });
    $(this).html(r);
    })
    }
    }

    1. hm apparently the span tags got removed in that post. Supposed to be:

      ” ” + match + “”;

      (obviously without the spaces)

      1. Okay one more try then I give up:

        “&lt span class=’highlight’ &gt” + match + “&lt / span &gt”;

        Hopefully everyone gets the point if this doesn’t work, you need to wrap the matched text in a span (or other element) that has the highlight class. That will add the highlight effect.

        1. Hi Jonathan, Thanks for your comments and appreciate the code.

Leave a Reply

Pin It on Pinterest

Shares