问题描述
我有一个正则表达式,比如说 /url.com \ /([A-Za-z] +)\ ..html /
,我想要用新字符串$ 1:f($ 1)
替换它,也就是说,使用带有两个插值的常量字符串,捕获的字符串和捕获的字符串的函数。
I have a regular expression, say /url.com\/([A-Za-z]+)\.html/
, and I would like to replace it with new string $1: f($1)
, that is, with a constant string with two interpolations, the captured string and a function of the captured string.
在JavaScript中执行此操作的最佳方法是什么? 最佳在这里意味着(1)最不容易出错,(2)在空间和速度方面最有效,(3)大多数惯用于JavaScript的特殊组合,特别强调#3。
What's the best way to do this in JavaScript? 'Best' here means some combination of (1) least error-prone, (2) most efficient in terms of space and speed, and (3) most idiomatically appropriate for JavaScript, with a particular emphasis on #3.
推荐答案
替换
方法可以。
例如:
str.replace(/regex/, function(match, group1, group2, index, original) {
return "new string " + group1 + ": " + f(group1);
});
这篇关于Javascript正则表达式:用f($ 1)替换$ 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!