使用$ 0来引用Javascript的String.replace中的整个匹配 [英] Using $0 to refer to entire match in Javascript's String.replace
问题描述
我在一组文本中突出显示搜索字符串的实例。我想在替换查询的不区分大小写的匹配时保留原始文本的大小写。以下是我的开始:
I'm highlighting instances of a search string within a set of text. I want to preserve the case of the original text while 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>');
但 $ 0
似乎不是used - 所有匹配的字符串都替换为$ 0。但我确实找到了另一种方法:
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?
推荐答案
使用 $&
而不是 $ 0
来引用整场比赛。我责备Perl。
Use $&
and not $0
to refer to the entire match. I blame Perl.
这篇关于使用$ 0来引用Javascript的String.replace中的整个匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!