' + phrase +...">

Smart lines

This works well for case-insensitive replacements:

str = str.replace(new RegExp(phrase, 'gi'), '<span style="color:red;">' + phrase + '</span>'); 

But I want the case when it was replaced, as indicated above, to not change.

+4
source share
2 answers

str = str.replace(new RegExp(phrase, 'gi'), '<span>$&</span>');

+1
source

Grab the phrase in brackets and use $1 in the replacement string, for example:

 'Foobar'.replace(/(foo)/gi, '<x>$1</x>') 

The result will be <x>Foo</x>bar

0
source

All Articles