Highlight text with jQuery

Here I am going to show how to highlight particular word within a block of text.
You can use this feature to:
– highlight the search terms on the page.
– highlight particular keywords dynamically on the page.
– highlight negative numeric values on block of page.

Below is the working example, enter the text in textbox and click on “highlight” button to highlight the text in the block.

 

Sample text for highlight.

Sample text for highlight1.

Let us take a the sample text

<div id="content-block">
  <p>  
    Sample text for highlight.
  </p>
  <p>  
    Sample text for highlight1.
  </p>
</div>
$(document).ready(function() {
 $('input[name="hbtn"]').click(function() {
     var o ={words:$('input[name="query"]').val()};
     highlight("content-block",  o);
  });
});

here is the code for highlight the word in block of text

function highlight(id, options) {
  var o = {
    words: '',
    caseSensitive: false,
    wordsOnly: true,
    template: '$1<span class="highlight">$2</span>$3'
  }, pattern;
  $.extend(true, o, options || {});

  if (o.words.length == 0) { return; }
  pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', o.caseSensitive ? "" : "ig");

  $('#'+id).each(function() {
    var content = $(this).html();
    if (!content) return;
    $(this).html(content.replace(pattern, o.template));
    });
  }


7 Comments

Add a Comment

Your email address will not be published. Required fields are marked *

Close Bitnami banner