用正则实现最简单的mustach语法:
let data={
a:1,
b:2
}
let str='this is a = {{a}},this is b = {{b}}'
function template(str,data) {
return str.replace(/\{\{(\w+)\}\}/g,function (findStr,$1) {
return data[$1]
})
}
console.log(template(str,data));
正则表达式的replace的第二个参数可以是一个函数,第一个参数时匹配的字符串内容,即{{a}},第二个参数是捕获的内部的内容就是a。