Javascript替换参考匹配组?

时间:2009-08-05 17:48:15

标签: javascript regex

我有一个字符串,例如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>")

有任何想法或建议吗?

3 个答案:

答案 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)

有关的替换字符串,通过与所指定的替换模式$。 这里简历:

enter image description here

链接到doc:here

"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")



注意:

如果要在替换字符串中包含$,请使用$$。与vscode代码段系统相同。