需要更换<wiki>this page</wiki>
to <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 中那样获取 matches[0]、matches[1]preg_replace_callback()
?
The replace函数的回调 https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter将匹配作为参数。
例如:
text = text.replace(/<wiki>(.+?)<\/wiki>/g, function(match, contents, offset, input_string)
{
return "<a href='wiki/"+contents.replace(/ /g, '_')+"'>"+contents+"</a>";
}
);
(第二个参数是第一个捕获组)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)