问题:实现template方法,替换模板中的变量
consttpl=`<p> hello, my name is <%= name%>, my age is <%= age %>`letdata={name:'jerry',age:18}letresult=template(tpl,data)console.log(result)//输出<p> hello, my name is jerry my age is 18实现:replace方法,正则匹配
- 简单替换:str.replace(匹配规则, 替换值);
- 函数替换:str.replace(匹配规则, 回调函数);
// 用正则表达式匹配所有占位符,然后对每个匹配项执行回调函数,返回最终要替换的值。
(\w+) 捕获组(关键部分):
- \w 匹配字母、数字、下划线([a-zA-Z0-9_]);
- '+'表示匹配 1 个或多个(确保变量名至少有 1 个字符);
- 用 () 包裹表示 “捕获”,后续回调函数能获取到这个匹配的变量名。
// match是匹配到的<%= name %>, 是被替换的目标;
// key是通过(\w+)捕获到的分组内容,如 name ;
// 回调函数的返回值会替换掉match对应的内容。
functiontemplate(tpl,data){returntpl.replace(/<%=\s*(\w+)\s*%>/g,(match,key)=>{returndata[key]??''//从data中取值,如果不存在则返回空字符串})}