mustache使用正则表达式实现
// this is {{name}} object; obj = { name: '123' }
function render(template, data) {
const reg = /\{\{(\w+)\}\}/g;
if (!reg.test(template)) {
return template;
}
// matched匹配的子串,key表示正则表达式中第一个括号的内容;后续可能有key2 key3 ...
const result = template.replace(reg, (matched, key) => {
return data[key];
});
return result;
}
const template = '我是{{name}},年龄{{age}}';
const data = {
name: '庆余年',
age: 1
}
console.log(render(template, data));
来源:CSDN
作者:小仙女爱吃虾滑
链接:https://blog.csdn.net/XiaChongYuFei/article/details/104186647