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: http://jsfiddle.net/4sGLL/

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: https://jsfiddle.net/pawmbude/

Leave a Comment

tech