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

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:

Leave a Comment