我有一个字符串,例如hello _there_
。我想使用 JavaScript 分别用<div>
和</div>
替换两个下划线。输出(因此)看起来像hello <div>there</div>
。该字符串可能包含多对下划线。
我正在寻找的方法是 在每场比赛中运行一个函数,就像Ruby一样:
"hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }
或能够引用匹配的组,再次以红宝石的方式完成:
"hello _there_".gsub(/_(.*?)_/, "<div>\\1</div>")
有任何想法或建议吗?
答案 0 :(得分:324)
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
哦,或者你也可以:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
答案 1 :(得分:28)
您可以使用replace
代替gsub
。
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
答案 2 :(得分:2)
有关的替换字符串,通过与所指定的替换模式$
。
这里简历:
链接到doc:here
"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")
注意:强>
如果要在替换字符串中包含$
,请使用$$
。与vscode代码段系统相同。