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))不起作用


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01