Javascript:将具有匹配项的函数传递给 replace( regex, func(arg) ) 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7192436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Passing a function with matches to replace( regex, func(arg) ) doesn't work
提问by Lorenz Lo Sauer
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
根据此站点,以下替换方法应该有效,但我持怀疑态度。 http://www.bennadel.com/blog/55-Using-Methods-in-Javascript-Replace-Method.htm
My code is as follows:
我的代码如下:
text = text.replace(
new Regex(...),
match() //$.. any match argument passed to the userfunction 'match',
// which itself invokes a userfunction
);
I am using Chrome 14, and do not get passed any parameters passed to the function match?
我正在使用 Chrome 14,并且没有传递任何传递给函数 match 的参数?
Update:
更新:
It works when using
它在使用时有效
text.replace( /.../g, myfunc() );
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.
JavaScript 解释器需要一个闭包, - 明显的用户函数似乎会导致范围问题,即不会调用进一步的用户函数。最初我想避免关闭以防止必要的内存消耗,但已经有了保护措施。
To pass the arguments to your own function do it like this (wherein the argument[0] will contain the entire match:
要将参数传递给您自己的函数,请这样做(其中参数 [0] 将包含整个匹配项:
result= text.replace(reg , function (){
return wrapper(arguments[0]);
});
Additionally I had a problem in the string-escaping and thus the RegEx expression, as follows:
此外,我在字符串转义和 RegEx 表达式中遇到了问题,如下所示:
/\s......\s/g
/\s......\s/g
is not the same as
不一样
new Regex ("\s......\s" , "g")
ornew Regex ('\s......\s' , "g")
new Regex ("\s......\s" , "g")
或者new Regex ('\s......\s' , "g")
so be careful!
所以要小心!
回答by Joe
$1 must be inside the string:
$1 必须在字符串内:
"string".replace(/st(ring)/, "gold ")
// output -> "gold ring"
with a function:
有一个功能:
"string".replace(/st(ring)/, function (match, capture) {
return "gold " + capture + "|" + match;
});
// output -> "gold ring|string"
回答by Miriam
I think you're looking for new RegExp(pattern, modifiers).
我认为您正在寻找新的 RegExp(模式,修饰符)。