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>"));
});
}
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>"));
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With