Javascript:将具有匹配项的函数传递给 replace( regex, func(arg) ) 不起作用 [英] Javascript: Passing a function with matches to replace( regex, func(arg) ) doesn't work
问题描述
根据此站点,以下替换方法应该可行,但我持怀疑态度.http://www.bennadel.com/blog/55-Using-Methods-in-Javascript-Replace-Method.htm
According to this site the following replace method should work, though I am sceptical. http://www.bennadel.com/blog/55-Using-Methods-in-Javascript-Replace-Method.htm
我的代码如下:
text = text.replace(
new Regex(...),
match($1) //$.. any match argument passed to the userfunction 'match',
// which itself invokes a userfunction
);
我使用的是 Chrome 14,并且没有传递任何传递给函数 match 的参数?
I am using Chrome 14, and do not get passed any parameters passed to the function match?
更新:
使用时有效
text.replace( /.../g, myfunc($1) );
JavaScript 解释器需要一个 闭包, - 明显的用户函数似乎会导致范围问题,即不会调用进一步的用户函数.最初我想避免关闭以防止必要的内存消耗,但已经有保护措施.
The JavaScript interpreter expects a closure, - apparent userfunctions seem to lead to scope issues i.e. further userfunctions will not be invoked. Initially I wanted to avoid closures to prevent necessary memory consumption, but there are already safeguards.
要将参数传递给您自己的函数,请这样做(其中参数 [0] 将包含整个匹配项:
To pass the arguments to your own function do it like this (wherein the argument[0] will contain the entire match:
result= text.replace(reg , function (){
return wrapper(arguments[0]);
});
此外,我在字符串转义和 RegEx 表达式中遇到了问题,如下所示:
Additionally I had a problem in the string-escaping and thus the RegEx expression, as follows:
/\s......\s/g
与
new Regex ("\s......\s" , "g")
或new Regex ('\s......\s' , "g")
所以要小心!
推荐答案
$1 必须在字符串内:
$1 must be inside the string:
"string".replace(/st(ring)/, "gold $1")
// output -> "gold ring"
带函数:
"string".replace(/st(ring)/, function (match, capture) {
return "gold " + capture + "|" + match;
});
// output -> "gold ring|string"
这篇关于Javascript:将具有匹配项的函数传递给 replace( regex, func(arg) ) 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!