Skip to content Skip to sidebar Skip to footer

Highlighting All Matching Words In Div From Text Input

I have made a function which highlights matching words in a div. but if there are two identical words separated by a different word then only the first word is highlight. so for ex

Solution 1:

You can pass a regular expression into replace() instead of the string, with the g modifier to make replace perform a global match.

if($('#search').val().length !== 0){
   $('.searchable').each(function(){
   var search_value = $("#search").val();
   var search_regexp = newRegExp(search_value, "g");
   $(this).html($(this).html().replace(search_regexp,"<span class = 'highlight'>"+search_value+"</span>"));
 });
}

Solution 2:

  1. Take care of regex special characters.

  2. Maintain uppercase & lowercase.

So taking care of above things with case insensitive search (in most cases, this is desired; otherwise just remove "i"), here is the final code...

if ($('#search').val().length !== 0) {
    $('.searchable').each(function() {
        //Handle special characters used in regexvar searchregexp = newRegExp($("#search").val().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "gi");

        //$& will maintain uppercase and lowercase characters.
        $(this).html($(this).html().replace(searchregexp, "<span class = 'highlight'>$&</span>"));
    });
}

And a fiddle.

Solution 3:

Here's a working jsfiddle for you. Basically, get the text from the div, split it on space, loop through the words and see if one matches.

var term = $('#search').val().trim().toLowerCase();
if (term.length > 0) {
    var source = $('.searchable').text();
    var words = source.split(' ');
    var output = '';
    $.each(words, function(idx, word) {
        if (term === word.toLowerCase()) {
            output += '<span class="highlight">' + word + '</span> ';
        } else {
             output += word + ' ';   
        }
    });

    $('.searchable').html(output);
}

Solution 4:

Use regular expression with :

  • global 'g' flag to replace all the matches
  • ignore case 'i' to match all cases

Do not forget to escape special characters

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

constSEARCH_VALUE = $("#search").val().trim();

if (SEARCH_VALUE.length > 0) {
  $('.searchable').each(function() {
    constDIV_TEXT_CONTENT = $('.searchable').text();
    constSPLIT_CONTENT = DIV_TEXT_CONTENT.split(" ");

    SPLIT_CONTENT.forEach((word, index) => {
      constSEARCH_REGEXP = newRegExp(escapeRegExp(SEARCH_VALUE), "gi")
      if (SEARCH_REGEXP.test(word))
        $(this).html($(this).html().replace(SEARCH_REGEXP, "<span class = 'highlight'>" + word + "               </span>"));
    });
  })
}

functionescapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
.highlight {
  font-weight: bold;
  color: green;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><inputid="search"type="text"value="BuRn"><divclass="searchable">burn baby burn</div>

Post a Comment for "Highlighting All Matching Words In Div From Text Input"