This question already has answers here:
JS to automatically convert text in parentheses with specific markup including match
(3个答案)
JavaScript/jQuery String Replace With Regex
(4个答案)
去年关闭。
我对数据库的描述如下:
我不想用
我尝试了这个:My Attempt
我知道我该如何吸引人,但我不知道如何只更换这些零件,然后再进行展示。
谢谢!
编辑:
我希望我的最终字符串为:
(3个答案)
JavaScript/jQuery String Replace With Regex
(4个答案)
去年关闭。
我对数据库的描述如下:
"And here is the {{dog}} which is chasing the {{cat}}"
我不想用
{{dog}}
代替它,而是用<span class="dog"/>
代替我尝试了这个:My Attempt
我知道我该如何吸引人,但我不知道如何只更换这些零件,然后再进行展示。
谢谢!
编辑:
var input = "And here is the {{dog}} which is chasing the {{cat}}";
var regex = /{{(.*?)}}/g;
var matches, output = [];
while (matches = regex.exec(input)) {
output.push(matches[1]);
}
我希望我的最终字符串为:
And here is the <span class="dog"/> which is chasing the <span class='cat'/>
最佳答案
您可以使用以下捕获组:$1
表示括号(捕获组)中匹配的文本,可以在replace
(MDN)中使用
const str = "And here is the {{dog}} which is chasing the {{cat}}"
const newStr = str.replace(/{{(\w+)}}/g, "<span class='$1' />")
console.log(newStr)