正则表达式实现render函数

请问下为什么没替换成功?

打印信息为:
name
/${name}/ 'xiaoming'
the age of ${name} is ${age}
age
/${age}/ 8
the 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); 
    }
    
  }
}
阅读 1.9k
2 个回答

$表示字符串的结尾,是特殊字符,使用RegExp的时候,需要使用两个\\转义:

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+"}");
      // var re = "${" + key + "}"; // 这块直接使用字符串就行,不用正则也可以
      console.log(re,data[key]);
      template = template.replace(re,data[key]);
      // console.log("test:",template.replace("${name}","xiaoming"));
      console.log(template); 
    }
  }
}
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;
  })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题