Highlighting Matching Text in Search Results with jQuery

Following on from a previous post Easy Search As You Type List Filtering with jQuery, I’ve added a new function/feature to this script – the ability to highlight the matching text in the search results. Here’s the pen:

See the Pen Easy Text Filtering with Matching Text Highlighted by Chris Smith (@chris22smith) on CodePen

The search/filter script is the same as the previous Text Filtering post. The part we’re looking at here is the highlight() function.

The function takes a text string – the text typed into the text box. It then finds the indexOf or character position of the matching text in the result’s text and splits this into three parts using slice() – the section before the matching text (beforeMatch), the matching text (matchText) and the section after the matching text (afterMatch). By wrapping the matching part in tags and then putting the various parts all back together again in one string we can add highlighting into the HTML.

About Chris Smith

Web developer specialising in frontend UI design @chris22smith
This entry was posted in filter(), jQuery, slice() and tagged , , , , , , , , , , , . Bookmark the permalink.

One Response to Highlighting Matching Text in Search Results with jQuery

  1. arjun menon says:

    hi
    how can i integrate your highlight function with this modified live search from your previous post.
    http://jsfiddle.net/rb7hm/4/

    thanks

Comments are closed.