Regular expression implements render function

could you tell me why the replacement is not successful?

print message:
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); 
    }
    
  }
}

$ represents the end of the string and is a special character. When using RegExp , you need to use two \ escape:

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;
  })
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e4761c-44c3b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e4761c-44c3b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?