tags:

views:

26

answers:

2

This works well for case insensitive replacements:

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

But what I do want is to not change case when replaced which above-mentioned does.

A: 

Capture the phrase with parenthesis, and use $1 in the replace string, eg:

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

Would result in <x>Foo</x>bar

reko_t
Kobi
I'm not sure what you mean. There is a capturing group, and `$1` refers to the first captured group.
reko_t
There's a capturing group after I edited your answer `:)`
Kobi
Ah oops, it seems like I forgot to add parenthesis around foo, and Kobi added them for me. Sorry about that!
reko_t
Either with capturing or without, it does not work.
Alex Polo
+1  A: 

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

grddev
This one works! Thanks! The one reko_t suggested does not work at least in my Opera.
Alex Polo