JavaScript - 字符串正则表达式反向引用
你可以在 JavaScript 中像这样反向引用:
var str = "123 $test 123";
str = str.replace(/(\$)([a-z]+)/gi, "$2");
这会(相当愚蠢)用“test”替换“$test”。但想象一下我想将 $2 的结果字符串传递给一个函数,该函数返回另一个值。我尝试这样做,但我没有得到字符串“test”,而是得到“$2”。有办法实现这一点吗?
// Instead of getting "$2" passed into somefunc, I want "test"
// (i.e. the result of the regex)
str = str.replace(/(\$)([a-z]+)/gi, somefunc("$2"));
You can backreference like this in JavaScript:
var str = "123 $test 123";
str = str.replace(/(\$)([a-z]+)/gi, "$2");
This would (quite silly) replace "$test" with "test". But imagine I'd like to pass the resulting string of $2 into a function, which returns another value. I tried doing this, but instead of getting the string "test", I get "$2". Is there a way to achieve this?
// Instead of getting "$2" passed into somefunc, I want "test"
// (i.e. the result of the regex)
str = str.replace(/(\$)([a-z]+)/gi, somefunc("$2"));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
像这样:
Like this:
将函数作为第二个参数传递给
replace
:根据 mozilla.org。
Pass a function as the second argument to
replace
:This capability has been around since Javascript 1.3, according to mozilla.org.
使用 ESNext,一个相当虚拟的链接替换器,但只是为了展示它是如何工作的:
Using ESNext, quite a dummy links replacer but just to show-case how it works :
注意:之前的答案缺少一些代码。现在已修复+示例。
我需要更灵活的正则表达式替换来解码传入的 JSON 数据中的 unicode:
Note: Previous answer was missing some code. It's now fixed + example.
I needed something a bit more flexible for a regex replace to decode the unicode in my incoming JSON data:
如果反向引用的数量可变,那么参数计数(和位置)也是可变的。 MDN 网络文档描述将函数指定为替换参数的以下语法:
例如,采用这些正则表达式:
此处不能使用“arguments”变量,因为它的类型为
Arguments
而不是Array 类型
所以它没有slice()
方法。If you would have a variable amount of backreferences then the argument count (and places) are also variable. The MDN Web Docs describe the follwing syntax for sepcifing a function as replacement argument:
For instance, take these regular expressions:
You can't use 'arguments' variable here because it's of type
Arguments
and no of typeArray
so it doesn't have aslice()
method.