模板替换变量
function tpl(template,data){ return template.replace(/{%([^%{}]+)%}/g,function(orgin,item){ item = item.replace(/^s+|s+$/,""); var params = []; if(item.indexOf('.') > -1){ params = item.split('.') } return params.reduce((a,b)=> { return a[b] },data) }) } var str = `<div class="{%data.className%}">{%data.name%}</div>` var d = {data: {name: 123,className:'hd'}} var t = tpl(str,d) console.log(t)