开发者

Smart String Replacements

开发者 https://www.devze.com 2023-01-11 05:23 出处:网络
This works well for case insensitive replacements: str = str.replace(new RegE开发者_如何学JAVAxp(phrase, \'gi\'), \'<span style=\"color:red;\">\' + phrase + \'</span>\');

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

0

精彩评论

暂无评论...
验证码 换一张
取 消