Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case-insensitive wrap substring with tags

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?

like image 663
Sean Anderson Avatar asked Aug 25 '13 03:08

Sean Anderson


2 Answers

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.

like image 88
Barmar Avatar answered Oct 02 '22 00:10

Barmar


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.

like image 21
mu is too short Avatar answered Oct 01 '22 22:10

mu is too short