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.
getSelection() Method in JavaScript. The window. getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.
The 'mark' tag If you surround any text inside of the mark tag, it will automatically get highlighted by the browser in this striking yellow color. That makes highlighting searched text quite a simple task then.
See "Escape Regular Expression Characters in String - JavaScript" for information about how to escape special regex characters, such as ()
EDIT: Also check out this older SO question that asks a very similar - almost identical - question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With