Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Any help much appreciated. Thanks for reading.

css

.highlight{
            font-weight:bold;
            color:green;
}

html

<input id = "search" type ="text" value = "burn">
<div class = "searchable">burn baby burn</div>

javascript

if($('#search').val().length !== 0){
   $('.searchable').each(function(){
   $(this).html($(this).html().replace($('#search').val(),"<span class = 'highlight'>"+$('#search').val()+"</span>"));
 });
}
like image 602
user2014429 Avatar asked Nov 30 '22 11:11

user2014429


1 Answers

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>"));
 });
}
like image 91
Danny Avatar answered Dec 10 '22 17:12

Danny