Javascript: Case insensitive highlighting of a searchterm


Lets say you have a page with searchresults base on the search term ‘foo’ and you want to highlight all appearances of that word in the results list html. Well, a simple replace function won’t work, because it will not take into account that some appearances of the word might be in uppercase of partially in uppercase. Also, using a /term/gi will not work because you would replace the uppercased word with the original term, which might be is in lowercase. So, this is the solution:

var html = '<ul><li>These are the foo fighters</li>';
html+='<li>Foo fighters are the best</li></ul>';
var term = 'foo';
var re = new RegExp('(' + term + ')', 'gi');
html = html.replace(re, '<span class="highlighted">$1</span>');

Obviously you can set any formatting on the highlighted class to make it appear the way you want in the browser.

About Sandor Voordes

I was born on the 17th of november 1974 in Groningen, a city in the far north of the Netherlands. I grew up for the larger part in the province of Groningen but lived for several soperate periods in Zambia and Mozambique. I am currently 35 years old, living together with my Israeli girlfriend in the beautiful city of Utrecht, dead center Netherlands.
This entry was posted in Javascript and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s