基于匹配的RegEx JavaScript动态替换数据



我有一个动态模板字符串,类似于以下内容:

There are {{num}} matches for the category {{category}}.

我还有一个这样的对象:

let data = {
"num": // some value
"category": // another value
}

如何用对象中的值替换每个模板变量,其中键是大括号中的文本。例如:

// example object
let data = {
"num": "six",
"category": "shoes"
}
// result
"There are six matches for the category shoes"

我尝试过以下几种:

messageRegEx = /{{(.*)}}/g
matchesMessage = template.replace(messageRegEx, data["$1"])

上面的代码将大括号中的所有文本实例替换为undefined。我研究了多个StackOverflow问题,但都没有解决这个问题。

幸运的是,replace()允许使用回调:

matchesMessage = template.replace(
/{{(.+?)}}/g,
(match, tag) => data[tag.trim()]
);
console.log(matchesMessage);
// "There are six matches for the category shoes."

所以,为了清楚起见,您有一个具有各种属性的对象,您只想将这些属性的值嵌入字符串中吗?

一种可能的解决方案是使用模板文字,它允许您将数据嵌入字符串中。基本上,将字符串括在反引号内,而不是单引号或双引号,然后用${}将表示数据的表达式括起来

最新更新