est字符串模版原理

let name = "minmin",age = 25;
let desc = `my name is ${name}, my age is ${age}`;

我们都知道,es6增加了字符串模版,方便了我们字符串拼接的麻烦,笔者之前也是只知道字符串模版,没有去深入的了解一下原理。

首先,我们看一下字符串模版转为es5语法后是什么样的

let name = "minmin",age = 25;

let dese = "my name is ".concat(name, "my age is ").concat(age)

 

其实es6内部的原理,只是将${name}进行替换,具体请看代码

let name = "minmin",age = 25;
let desc = "my name is ${name}, my age is ${age}";
function replace(desc){
  return desc.replace(/\$\{([^}]+)\}/g,function(matched,key){
    // matched 匹配的字符串${name}
    // childItem 匹配的分组[^}]里的内容
    return eval(key);
  })
}
console.log(replace(desc))

 

你可能感兴趣的:(前端面试必备知识)