【发布时间】:2017-12-27 09:07:36
【问题描述】:
我有一个描述产品的具有无数属性的对象,例如颜色和品牌。我正在寻找一种以段落形式动态生成产品描述的方法(因为 API 不提供),我想出了一种方法,方法是编写在括号中包含“道具”@987654326 的“模板” @。我编写了一个函数来“解析”模板,通过将“props”替换为键的值来注入字符串中的对象属性。
例如:
对象:{color: 'white'}
模板:"The bowl is {{color}}."
结果:"The bowl is white."
由于某种原因,我的解析功能不起作用。 {{general_description}} 未解析。
var obj = {
brand: "Oneida",
general_description: "Plate",
material: "China",
color: "Bone White",
product_width: "5\""
};
const templatePropRe = /{{(\w*)}}/g;
const parse = (template) => {
while ((result = templatePropRe.exec(template)) !== null) {
let match = result[0],
key = result[1];
template = template.replace(match, obj[key]);
}
return template;
}
console.log(parse('This {{color}}, {{material}} {{general_description}} supplied by {{brand}} has a width of {{product_width}}.'));
我按照示例 > 查找连续匹配项下的 MDN docs 中提供的示例进行操作。它说我需要先将正则表达式存储在一个变量中(例如,templatePropRe),因为该表达式不能处于 while 循环条件中,否则它将无限循环。但是,如果我这样做,我的问题就解决了。见here...没坏处。
我使用String.prototype.match 重写了该函数,它按预期工作,但我无法访问捕获,因此我需要先使用stripBrackets 去掉括号。请参阅使用 match here 的工作示例。
我想知道的是为什么我的使用RegExp.prototype.exec 的parse() 函数不能正常工作?
【问题讨论】:
标签: javascript regex string match exec