admin管理员组文章数量:1129437
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.
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>" }
Or be able to reference a matched group, again the way it can be done in ruby:
"hello _there_".gsub(/_(.*?)_/, "<div>\\1</div>")
Any ideas or suggestions?
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.
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>" }
Or be able to reference a matched group, again the way it can be done in ruby:
"hello _there_".gsub(/_(.*?)_/, "<div>\\1</div>")
Any ideas or suggestions?
Share Improve this question edited Aug 3, 2018 at 4:00 user6269864 asked Aug 5, 2009 at 17:48 Sinan TaifourSinan Taifour 10.8k3 gold badges34 silver badges31 bronze badges3 Answers
Reset to default 531"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
Oh, or you could also:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
For the replacement string and the replacement pattern as specified by $
.
here a resume:
link to doc : here
"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")
Note:
If you want to have a $
in the replacement string use $$
. Same as with vscode snippet system.
本文标签: regexJavascript replace with reference to matched groupStack Overflow
版权声明:本文标题:regex - Javascript replace with reference to matched group? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736746428a1950801.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论