例一:
function render(template, data) {
const reg = /\{\{(\w+)\}\}/
if (reg.test(template)) {
const name = reg.exec(template)[1]
template = template.replace(reg, data[name])
return render(template, data)
}
return template
}
let template = '我是:{{name}},年龄:{{age}},性别:{{sex}}';
let person = {
name: 'xiaoming',
age: 12,
sex: '女'
}
console.log(render(template, person))
// ==============================================
// 写法二
function render(template, data) {
const reg = /\{\{(\w+)\}\}/g
let str = template.replace(reg, (match, key) => data[key])
return str
}
例二:
const year = '2021';
const month = '10';
const day = '01';
let template = '${year}-${month}-${day}';
let context = { year, month, day };
const str = render(template)(context);
console.log(str) // 2021-10-01
function render(template) {
return function(context) {
return template.replace(/\$\{(.*?)\}/g, (match, key) => context[key]);
}
}