Search code examples
javascriptjqueryhighlighting

javascript hightlight text strings


Using a small plugin to highlight some text that a user searches for on my application:

Johann Burkard Text Highlighting

I am able to use this to highlight a single text string by taking the value of the an input field and passing this to the plugin as a variable:

$(function() { 
    var hightLightme = $("input#searchterm").val();
    $('p').highlight(hightLightme);
});

This works fine for the likes of 'stackoverflow' but my search field has the capability of searching for multiple keywords, i.e. stackoverflow, web, dave where the comma acting as an 'and operator'

As the plugin stands it is looking for 'stackoverflow, web, dave' as an exact string and I am at a loss as to how I can code this so it breaks the keywords down and passes them to the plugin as individual keywords to be highlighted?


Solution

  • Use This instead.

     $(function() { 
    
         var arrayOfKeyWords= $("input#searchterm").val().split(',');
        for (var i=0;i<arrayOfKeyWords.length;i++)
         {
              $('p').highlight(arrayOfKeyWords[i]);
            }
    
    });