显示有误

博客园 首页 新随笔 联系 订阅 管理

1.string.replace常用来通过正则表达式来替换字符串的某个或某些字符,形成一个新的字符串,例如:

 

 

 

 

 

 2.其实它还有更强大的功能,那就是模板编译,此时需要传入一个回调函数作为其第二个参数,第一个参数仍然为一个正则表达式,例如

let template='<div data-id={{id}}>{{name}}</div>';
let newstr=template.replace(/\{\{(\w+)\}\}/g,function(node,key){
   console.log('key',key)//匹配到的模板中的变量名
   console.log('node',node)//匹配到的内容
    return {
        name:'june',
        id:1
     }[key]
})
console.log(newstr) //编译后的模板

  控制台结果如下:

 


posted on 2021-09-15 16:42  显示有误  阅读(75)  评论(0编辑  收藏  举报