请封装一个 strRender 函数,用来实现模板字符串解析功能。
strRender 函数接收两个参数,第一个参数是模板字符串 str,第二个参数是需要传入的
data,最终返回一个把模板中的变量替换了的新字符串。
const str = "My name is ${name}, I am ${age} years old, I come from ${country}";
const data = {
name: "zhangsan",
age: "18",
country: "China",
};
console.log(strRender(str, data));
// 'My name is zhangsan, I am 18 years old, I come from China'
function strRender(str, data) {
const reg = /\$\{(\w+)\}/; // 匹配 ${多个字符} 这样的字符串
while (reg.test(str)) {
const key = str.match(reg)[1];
//match()得到的是一个对象如下一行内容所示 match()[1]即是我们想要的key值
//['${name}', 'name', index: 11, input: 'My name is ${name}, I am ${age} years old, I come from ${country}', groups: undefined]
str = str.replace(re, data[key]);
//replace() 如果第二个参数是字符串 则在原字符串中 讲第一个参数的值改为第二个参数值
}
return str;
}
function strRender(str, data) {
const re = /\$\{(\w+)\}/g;
//g:global 表示全文查找
return str.replace(re, (match, key) => data[key]);
// replace() 第二个参数如果是函数 函数的返回值即相当于方法一中的第二个参数 使用方法的好处是 每次匹配到都会执行一次这个函数
}