关于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 @ 2019-04-10 15:02  *朝晖  阅读(1398)  评论(0编辑  收藏  举报