在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ 正則表達式實現(xiàn)render函數(shù)

正則表達式實現(xiàn)render函數(shù)

請問下為什么沒替換成功?

打印信息為:
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); 
    }
    
  }
}
回答
編輯回答
菊外人

$表示字符串的結尾,是特殊字符,使用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); 
    }
  }
}
2017年7月14日 03: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;
  })
}
2017年1月19日 11:20