关于js replace 第二个参数是函数时,函数参数解析

function formateString(str,obj) {
    return str.replace(/\{#(\w+)#\}/g,function(match,key,index,source){
        console.log(arguments);
        return obj[key]
    })
}
var string='<div>{#content#}</div>';
formateString(string,{content:'helloWorld'});

解析:

  match 是匹配到字符串 示例中 为{#content#}

  key 是捕获分组中内容(无分组时不存在),正则表达式中小括号内的内容为一个分组,所以示例中为content

  index 是字符串的下表也就是示例中{的下标即5

  source 是原字符串 示例中为<div>{#content#}</div>

posted @ 2020-06-11 10:54  smil、梵音  阅读(242)  评论(0编辑  收藏  举报