Javascript:传递具有匹配项的函数以替换(正则表达式,func(arg))不起作用

根据该站点,以下替换方法应该可以工作,尽管我对此表示怀疑.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,并且没有得到传递给函数匹配的任何参数?

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]);
});

另外我在字符串转义和正则表达式中遇到了问题,如下所示:

Additionally I had a problem in the string-escaping and thus the RegEx expression, as follows:

/s......s/g

新正则表达式 ("s.​​.....s" , "g")
新正则表达式 ('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"

相关文章