Javascript: Passing a function with matches to replace( regex, func(arg) ) doesn#39;t work(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"
这篇关于Javascript:传递具有匹配项的函数以替换(正则表达式,func(arg))不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript:传递具有匹配项的函数以替换(正则表达式,func(arg))不起作用


- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01