Javascript: highlighting part of a line with <b> tags
I am trying to highlight a match in a string by inserting tags <b>around the corresponding substring. For example, if the request is "cat", then:
"I have a cat."
should become:
"I have a <b>cat</b>."
Similarly, if the request is a "stack overflow", then:
"Qaru is great."
should become:
"<b>Stack Overflow</b> is great."
In other words, I have to keep the case of the original string, but not case sensitive when matching.
One thing I have tried so far:
var regex = new RegExp('(' + query + ')', 'i');
return strResult.replace(regex, '<b>$1</b>');
However, this raises an exception at run time if the request has any brackets in it, and I think it would be too much trouble to try to avoid all possible regex characters.
+5