用匹配替换回调函数 [英] replace callback function with matches
本文介绍了用匹配替换回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要将< wiki>此页< / wiki>
替换为< a href ='wiki / this_page'>此页< ; / a>
使用回调函数:
need to replace <wiki>this page</wiki>
to <a href='wiki/this_page'>this page</a>
using callback function:
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>此页< / wiki>< / a>
result is that tag <wiki>
is preserved (full match) - <a href='wiki/<wiki>this_page</wiki>'><wiki>this page</wiki></a>
有没有办法获得匹配[0],匹配[1],如PHP的 preg_replace_callback()
?
Is there a way to get matches[0], matches[1] as in PHP's preg_replace_callback()
?
推荐答案
replace
function's callback 将匹配作为参数。
The replace
function's callback takes the matches as parameters.
例如:
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)
这篇关于用匹配替换回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文