猿问

正则表达式实现render函数

请问下为什么没替换成功?
打印信息为: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);
}
}
}
红糖糍粑
浏览 567回答 2
2回答

慕容森

$表示字符串的结尾,是特殊字符,使用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);}}}

眼眸繁星

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;})}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答