Skip to content

Javascript: highlight substring keeping original case but searching in case insensitive mode

I’m trying to write a “suggestion search box” and I cannot find a solution that allows to highlight a substring with javascript keeping the original case.

For example if I search for “ca” I search server side in a case insensitive mode and I have the following results:




I would like to view the search string in all the previous words, so the result should be:




I tried with the following code:

var reg = new RegExp(querystr, 'gi');
var final_str = 'foo ' + result.replace(reg, '<b>'+querystr+'</b>');

But obviously in this way I loose the original case!

Is there a way to solve this problem?


Use a function for the second argument for .replace() that returns the actual matched string with the concatenated tags.

Try it out:

reg = new RegExp(querystr, 'gi');
       // The str parameter references the matched string
       //    --------------------------------------v
final_str = 'foo ' + result.replace(reg, function(str) {return '<b>'+str+'</b>'});
$('#' + id).html(final_str);‚Äč

JSFiddle Example with Input: