Javascript 替换参考匹配组?

IT技术 javascript regex
2021-01-24 05:37:45

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

有什么想法或建议吗?

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

哦,或者你也可以:

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

Liran H 编辑: 对于包括我在内的其他六个人,$1没有工作,而\1有。

我发现 \1 工作但 $1 没有,尽管我使用的是 RegExp 变体:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
2021-03-15 05:37:45
replacementValue可以是一个函数,并根据捕获组传递不同的参数?惊人!
2021-04-05 05:37:45
Javascript 使用$1而不是\1? 有人会提供指向文档的链接吗?
2021-04-10 05:37:45
@CalculatorFeline 说“正则表达式本身”并不能确定是哪一个,因为有人可能试图使用正则表达式进行替换。一定有很多人试图做到这一点:"hello _there_".replace(/_(.*?)_/, /<div>\1<\/div>/)
2021-04-12 05:37:45
2021-04-12 05:37:45

您可以使用replace代替gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
您可以删除反斜杠。
2021-04-07 05:37:45

对于由 指定的替换字符串和替换模式$这里有一份简历:

在此处输入图片说明

链接到文档:这里

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



笔记:

如果您想$在替换字符串中使用$$. 与 vscode 片段系统相同。