本文介绍了Javascript替换参考匹配组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,例如 hello _there _
。我想分别用< div>
和< / div>
替换两个下划线,使用的JavaScript 即可。输出(因此)看起来像 hello< div>那里< / div>
。该字符串可能包含多对下划线。
I have a string, such as hello _there_
. I'd like to replace the two underscores with <div>
and </div>
respectively, using JavaScript. The output would (therefore) look like hello <div>there</div>
. The string might contain multiple pairs of underscores.
我正在寻找的方法是 在每场比赛中运行一个函数,顺便说一下Ruby做到了:
What I am looking for is a way to either run a function on each match, the way Ruby does it:
"hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }
或能够引用匹配的组,再次以它的方式可以在ruby中完成:
Or be able to reference a matched group, again the way it can be done in ruby:
"hello _there_".gsub(/_(.*?)_/, "<div>\\1</div>")
任何想法或建议?
推荐答案
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
哦,或者你也可以:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
这篇关于Javascript替换参考匹配组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!