javascriptjqueryhtmlhighlighting

Search and Highlight in jQuery


I would like to search and highlight text using jQuery/Java Script.

sample HTML 1:

<div id="div1"><b>Good</b> <b>Morning</b> </div>
<div id="div2">Good Evening</div> 
<div id="div3">Good Morning</div>Searched String = "Good Morning"

When i search for String "Good Morning", Both the contents in div1 and div3 should get highlighted. ie. the output html should be

<div id="div1"><span class="highlight"><b>Good</b> <b>Morning</b> </span></div>
<div id="div2">Good Evening</div> 
<div id="div3"><span class="highlight">Good Morning</span></div>

I have used the plugin https://raw.github.com/bartaz/sandbox.js/master/jquery.highlight.js to enclose searched content inside span. But only div3 is highlighted. Please help.


Solution

  • http://jsfiddle.net/UPs3V/291/

     var src_str = $("#test").text();
    var term = "my text";
    term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*");
    var pattern = new RegExp("("+term+")", "gi");
    
    src_str = src_str.replace(pattern, "<mark>$1</mark>");
    src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4");
    
    $("#test").html(src_str);
    

    try this one it may help you