I am trying to write some code that will match words typed into a text input with words in div's with the class 'searchable' and highlights these words. What I have now works if one or more word matches and there are no words which don't match. For example, if the searchable div had the phrase: hello world
and in the input was hello world
it would highlight both. If the input had just hello
, it would highlight that word. But if the input had hello mars
, it would not highlight the word hello
, because mars
is not in the string. this jsFiddle demonstrates this. Any ideas much appreciated. Here is the code. Thank you.
javaScript:
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>"));
});
}
html:
<input type = "text" id = "search" value = "hello mars">
<div class = "searchable">hello world</div>