0

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>
user2014429
  • 2,497
  • 10
  • 35
  • 49

1 Answers1

1

Something like this:

// http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
String.prototype.pregQuote = function()
{
  return this.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

var keyword = $("#search").val();
var searchRegex = new RegExp( '(' + keyword.pregQuote() + ')' , "ig" );

$('.searchable').each(function(){
  var html = $(this).html();
  html = html.replace( searchRegex , '<span class="highlight">$1</span>');
  $(this).html( html );
});
oliakaoil
  • 1,615
  • 2
  • 15
  • 36