Javascript 用匹配替换回调函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3395843/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:27:40  来源:igfitidea点击:

replace callback function with matches

javascript

提问by Qiao

need to replace <wiki>this page</wiki>to <a href='wiki/this_page'>this page</a>
using callback function:

需要替换<wiki>this page</wiki><a href='wiki/this_page'>this page</a>
使用回调函数:

text = text.replace(/<wiki>(.+?)<\/wiki>/g, function(match)
    {
        return "<a href='wiki/"+match.replace(/ /g, '_')+"'>"+match+"</a>";
    }
);

result is that tag <wiki>is preserved (full match) - <a href='wiki/<wiki>this_page</wiki>'><wiki>this page</wiki></a>

结果是标签<wiki>被保留(完全匹配) -<a href='wiki/<wiki>this_page</wiki>'><wiki>this page</wiki></a>

Is there a way to get matches[0], matches[1] as in PHP's preg_replace_callback()?

有没有办法像在 PHP 中一样获取匹配 [0]、匹配 [1] preg_replace_callback()

回答by SLaks

The replacefunction's callbacktakes the matches as parameters.

replace函数的回调将匹配项作为参数。

For example:

例如:

text = text.replace(/<wiki>(.+?)<\/wiki>/g, function(match, contents, offset, input_string)
    {
        return "<a href='wiki/"+contents.replace(/ /g, '_')+"'>"+contents+"</a>";
    }
);

(The second parameter is the first capture group)

(第二个参数是第一个捕获组)