需要更换<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>";
}
);
结果是标签 <wiki>
保留(完全匹配)- <a href='wiki/<wiki>this_page</wiki>'><wiki>this page</wiki></a>
有没有办法像 PHP 的 preg_replace_callback()
那样获取 matches[0]、matches[1] ?
最佳答案
replace
function's callback将匹配项作为参数。
例如:
text = text.replace(/<wiki>(.+?)<\/wiki>/g, function(match, contents, offset, input_string)
{
return "<a href='wiki/"+contents.replace(/ /g, '_')+"'>"+contents+"</a>";
}
);
(第二个参数为第一个捕获组)
关于javascript - 用匹配项替换回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3395843/