javascriptjqueryhtmlcss

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 example if the search criterion was the word "burn", and in the text was the sentence "burn baby burn", I would want it to highlight both "burn"'s. this jsFiddle demonstrates how it only highlights the first "burn". Here is the code below also.

if ($('#search').val().length !== 0) {
  $('.searchable').each(function() {
    $(this).html($(this).html().replace($('#search').val(), "<span class = 'highlight'>" + $('#search').val() + "</span>"));
  });
}
.highlight {
  font-weight: bold;
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input id = "search" type ="text" value = "burn">
<div class="searchable">burn baby burn</div>


Solution

  • 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 = new RegExp(search_value, "g");
       $(this).html($(this).html().replace(search_regexp,"<span class = 'highlight'>"+search_value+"</span>"));
     });
    }