var searchText = "hello world";
var searchTextRegExp = new RegExp(searchText , "i"); // case insensitive regexp
var text = "blahblah Hello Worldz";
text.replace(searchTextRegExp , '<match>' + searchText + '</match>');
I'm trying to improve this bit of code. Currently, it lower cases Hello World because it is using searchText as the replacement value.
I'm hoping to just wrap Hello World with the tags and not modify its upper or lowercaseness while still maintain a case-insensitive search.
What's a good way to do this? string.indexOf is case-sensitive I believe -- which makes things a bit more complicated I think?
Inside the replacement text, you can use $&
to refer to whatever was matched by the regexp.
text = text.replace(searchTextRegExp , '<match>$&</match>');
You can also use $1
, $2
, etc. to refer to the matches for capture groups in the regexp.
The replacement string can contain patterns, in particular $&
:
$&
Inserts the matched substring.
So you can say:
text.replace(searchTextRegExp , '<match>$&</match>').
to use the exact string that was found in text
.
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