为了账号安全,请及时绑定邮箱和手机立即绑定

正则表达式实现render函数

正则表达式实现render函数

富国沪深 2019-03-30 11:19:32
请问下为什么没替换成功?打印信息为:name/${name}/ 'xiaoming'the age of ${name} is ${age}age/${age}/ 8the age of ${name} is ${age}const template = "the age of ${name} is ${age}";const data = { name: "xiaoming", age: 8};console.log(render(template, data));// 输出: "the age of xiaoming is 8"function render(template,data) {  for (key in data) {    if(key) {      console.log(key);      var re = new RegExp("\$\{"+key+"\}");      console.log(re,data[key]);      var ans = template.replace(re,data[key]);      // console.log("test:",template.replace("${name}","xiaoming"));      console.log(ans);     }      }}
查看完整描述

2 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

const template = "the age of ${name} is ${age}";

const data = { name: "xiaoming", age: 8};

console.log(render(template, data));


function render(template,data) {

  var reg = /\$\{(\w*)\}/g;

  

  return template.replace(reg,function(a,b){

    var val = data[b];

    //可以抛出错误也可以给个默认空字符串

    if(val===undefined)throw new TypeError('Cannot read property "'+b+'" of undefined');

    return val;

  })

}


查看完整回答
反对 回复 2019-04-04
  • 2 回答
  • 0 关注
  • 486 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信