我们知道在ES6中,新增了反引号语法,使得反引号中可以插入变量,解析时可以将变量替换成实际值并且拼接到字符串中。这种模板字符串中变量的识别可以手写一个函数来简单实现:
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}},来自{{address}},今年{{age}}岁'
let person = {
name: '小明',
address: '北京',
age: 20
}
console.log(render(template, person))
// 我叫小明,来自北京,今年20岁
代码大致思想:
- 定义一个函数,传递两个参数,一个是包含有变量标识符的模板字符串,一个是提供数据的对象;
- 定义一个正则表达式,用来识别
{{}}
中的变量标识符,识别到一个,就将变量标识符用真正数据替换,接着递归执行,知道所有变量都替换完毕;