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;
  })
}
Menu