2

This is a simple search function with highlight effect, however, it highlight the whole word instead of the matched strings.

How can I make it like doing ctrl+f in browser that highlights just part of the matched word?

$(document).ready(function(){
    $('input').keyup(function(){

       $("ul li").removeClass('hightlight');

       var searchInput = $(this).val();

        if(searchInput !== ""){
           $("ul li:contains('" + searchInput + "')").addClass('hightlight');
        }

    });
});

My code online:

http://jsfiddle.net/dennisboys/5ZEf7/1/

Dennisboys
  • 583
  • 3
  • 9
  • 22
  • possible duplicate of [How to highlight text using javascript](http://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript) – zb' Feb 05 '13 at 08:18

2 Answers2

4

Use following javascript:

$(document).ready(function(){
    $('input').keyup(function(){

       var searchInput = $(this).val();

       $('.hightlight').contents().unwrap();

       if(searchInput !== ""){
            $("ul li:contains('" + searchInput + "')").each(function(i, e) {
                var text = $(this).text().replace(new RegExp(searchInput, 'gm'), '<span class="hightlight">' + searchInput + '</span>');
                $(this).html(text);
            })
        }

    });
});
Alex G.P.
  • 9,609
  • 6
  • 46
  • 81
  • If a word contains two occurence of search string it will highlight first only unlike chrome where all occurences are highlight. I hope you can do this withe ease – Moons Feb 05 '13 at 08:30
  • Yep, I missed it, thank you for reminder =) Replaced search string with regexp. – Alex G.P. Feb 05 '13 at 08:34
1

Here's a working demo with the required HTML and css. http://jsfiddle.net/BHqTr/

$("#search").on( "keyup", function() {

        $("#items li span").contents().unwrap();

        $("#items li").each(function(){
            var search = $("#search").val();
            var item = $(this);

            var text = item.text();

            var regex = new RegExp(search, 'g');
            text = text.replace(regex, "<span class='highlight'>"+search+"</span>");
            item.html(text);
        });
    });

EDIT:

This looks like a copy of the previous answer, can be removed if required.

KBN
  • 2,915
  • 16
  • 27