2

我有来自数据库的描述如下:

"And here is the {{dog}} which is chasing the {{cat}}"

而不是让{{dog}}我想用<span class="dog"/>

我试过这个:我的尝试

我知道如何提取,但我不知道如何仅更换这些部件然后进行展示。

谢谢!

编辑 :

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'/>

4

2 回答 2

4

您可以使用这样的捕获组:

$1表示括号内匹配的文本(捕获组),可用于replaceMDN

const str = "And here is the {{dog}} which is chasing the {{cat}}"
const newStr = str.replace(/{{(\w+)}}/g, "<span class='$1' />")

console.log(newStr)

于 2019-02-05T15:08:55.830 回答
1

使用正则表达式替换和捕获您想要的文本。

const data = "And here is the {{dog}} which is chasing the {{cat}}";

const res = data.replace(/\{{2}([a-z]+)\}{2}/g, '<span class="$1">$1</span>');

document.body.innerHTML = res;
span {
  background-color: blue;
  color: white;
}

于 2019-02-05T15:10:24.480 回答