This works well for case insensitive replacements:
str = str.replace(new RegE开发者_如何学JAVAxp(phrase, 'gi'), '<span style="color:red;">' + phrase + '</span>');
But what I do want is to not change case when replaced which above-mentioned does.
str = str.replace(new RegExp(phrase, 'gi'), '<span>$&</span>');
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
精彩评论