请问下为什么没替换成功?打印信息为:name/${name}/'xiaoming'theageof${name}is${age}age/${age}/8theageof${name}is${age}consttemplate="theageof${name}is${age}";constdata={name:"xiaoming",age:8};console.log(render(template,data));//输出:"theageofxiaomingis8"functionrender(template,data){for(keyindata){if(key){console.log(key);varre=newRegExp("\$\{"+key+"\}");console.log(re,data[key]);varans=template.replace(re,data[key]);//console.log("test:",template.replace("${name}","xiaoming"));console.log(ans);}}}
2 回答
慕容森
TA贡献1853条经验 获得超18个赞
$表示字符串的结尾,是特殊字符,使用RegExp的时候,需要使用两个\\转义:consttemplate="theageof${name}is${age}";constdata={name:"xiaoming",age:8};console.log(render(template,data));//输出:"theageofxiaomingis8"functionrender(template,data){for(keyindata){if(key){console.log(key);varre=newRegExp("\\${"+key+"}");//varre="${"+key+"}";//这块直接使用字符串就行,不用正则也可以console.log(re,data[key]);template=template.replace(re,data[key]);//console.log("test:",template.replace("${name}","xiaoming"));console.log(template);}}}
眼眸繁星
TA贡献1873条经验 获得超9个赞
consttemplate="theageof${name}is${age}";constdata={name:"xiaoming",age:8};console.log(render(template,data));functionrender(template,data){varreg=/\$\{(\w*)\}/g;returntemplate.replace(reg,function(a,b){varval=data[b];//可以抛出错误也可以给个默认空字符串if(val===undefined)thrownewTypeError('Cannotreadproperty"'+b+'"ofundefined');returnval;})}
添加回答
举报
0/150
提交
取消