gpt4 book ai didi

javascript - 正则表达式 : How to replace the matched text with a HTML element in JavaScript?

转载 作者:行者123 更新时间:2023-11-29 16:32:30 25 4
gpt4 key购买 nike

我有一个来自数据库的描述,如下所示:

"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)

关于javascript - 正则表达式 : How to replace the matched text with a HTML element in JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com