开发者

Using $0 to refer to entire match in Javascript's String.replace

开发者 https://www.devze.com 2023-01-20 21:13 出处:网络
I\'m highlighting instances of a search string within a set of text. I want to preserve the case of the original text whi开发者_JAVA技巧le replacing a case-insensitive match of the query. Here\'s what

I'm highlighting instances of a search string within a set of text. I want to preserve the case of the original text whi开发者_JAVA技巧le replacing a case-insensitive match of the query. Here's what I started with:

text.replace(new RegExp('(' + query + ')', 'ig'), '<em>$1</em>');

In this case, I'd need to escape query to prevent parentheses from breaking the submatch, so I thought I'd try:

text.replace(new RegExp(query, 'ig'), '<em>$0</em>');

But $0 doesn't seem to be used - all matched strings are replaced with $0. I did find an alternative, however:

text.replace(new RegExp(query, 'ig'), function(match) { return '<em>' + match + '</em>'; });

I'm not a huge fan of how this looks, though. How would you recommend doing this type of string replacement?


Use $& and not $0 to refer to the entire match. I blame Perl.


use $$0 instead of $0

str.replace(/\$/,'$$')
0

精彩评论

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