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>