需要更换<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>";
}
);
Run Code Online (Sandbox Code Playgroud)
结果是该标签<wiki>被保留(完全匹配) -<a href='wiki/<wiki>this_page</wiki>'><wiki>this page</wiki></a>
有没有办法获得匹配[0],匹配[1],就像在PHP中一样preg_replace_callback()?
SLa*_*aks 77
该replace函数的回调需要比赛作为参数.
例如:
text = text.replace(/<wiki>(.+?)<\/wiki>/g, function(match, contents, offset, input_string)
{
return "<a href='wiki/"+contents.replace(/ /g, '_')+"'>"+contents+"</a>";
}
);
Run Code Online (Sandbox Code Playgroud)
(第二个参数是第一个捕获组)