在 Javascript 的 String.replace 中使用 $0 来引用整个匹配项 [英] Using $0 to refer to entire match in Javascript's String.replace

查看:13
本文介绍了在 Javascript 的 String.replace 中使用 $0 来引用整个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一组文本中突出显示搜索字符串的实例.我想在替换不区分大小写的查询匹配时保留原始文本的大小写.这是我的开始:

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>');

在这种情况下,我需要转义 query 以防止括号破坏子匹配,所以我想我会尝试:

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 似乎没有被使用——所有匹配的字符串都被替换为 $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.

这篇关于在 Javascript 的 String.replace 中使用 $0 来引用整个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆