I'm trying to highlight a match in a string by inserting <b>
tags around the matching substring. For example, if the query is "cat" then:
"I have a cat."
should become:
"I have a <b>cat</b>."
Likewise, if the query is "stack overflow", then:
"Stack Overflow is great."
should become:
"<b>Stack Overflow</b> is great."
In other words, I have to preserve the case of the original string, but not be case-sensitive when matching.
One thing I was trying so far is:
var regex = new RegExp('(' + query + ')', 'i');
return strResult.replace(regex, '<b>$1</b>');
However, this causes a runtime exception if query has any parenthesis in it, and I think it'd be too much hassle to attempt to escape all the possible regular expression characters.