/* 实现将字符串中的特定字符串替换为obj的对应属性 */ var greeting = 'My name is ${name}, age ${age}, I am a ${job.jobName}'; var employee = { name: 'XiaoMing', age: 11, job: { jobName: 'designer', jobLevel: 'senior' } }; var result = greeting.render(employee); console.log(result);// My name is XiaoMing,age 11, I am a designer
解决方案一:采用正则表达式
1 2 3 4 5 6 7
String.prototype.render = function (obj){ returnthis.replace(/\$\{(\w+|\w+\.\w+)\}/g, match => { var keys = match.replace("${", "").replace("}", "").split("."); var result = keys.reduce((acc, cv) => acc[cv], obj); return result === undefined ? match : result; //如果存在指定的属性则替换,否则不替换 }) }