我有一个字符串,比如hello _there。我想用JavaScript分别用<div>和</div>替换这两个下划线。输出将(因此)看起来像hello <div>there</div>。字符串可能包含多对下划线。

我正在寻找的是一种方法,可以在每个匹配上运行一个函数,就像Ruby那样:

"hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }

或者能够引用一个匹配的组,同样可以在ruby中实现:

"hello _there_".gsub(/_(.*?)_/, "<div>\\1</div>")

有什么想法或建议吗?


当前回答

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';
})

哦,或者你也可以:

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

其他回答

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';
})

哦,或者你也可以:

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

你可以用replace代替gsub。

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

替换字符串和替换模式,由$。 以下是简历:

链接到doc:这里

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

注意:

如果你想在替换字符串中使用$,请使用$$。与vscode snippet系统相同。