首页 > js的replace函数入参为function时的疑问

js的replace函数入参为function时的疑问

(function (window) {    
        function fn(str) {    
            this.str = str;    
        }    
        fn.prototype.format = function () {
            var arg = arguments;
            return this.str.replace(/\{(\d+)\}/g, function (a, b, c, d) {  
            console.log(a + "/////" + b + "//////" + c + "/////" + d);  // b为什么是0,1,2
                return arg[b] || '';    
            });    
        }    
        window.fn = fn;    
    })(window);    
    // use    
    (function(){    
        var t = new fn('<p><a href="{0}">{1}</a><span>{2}</span></p>');  
        console.log( t.format('http://www.alibaba.com', 'Alibaba', 'Welcome') );    
    })();  

如上,请问输出b为什么是"{}"里的内容


因为这对括号

第一个参数为正则所匹配到的内容, 第二个及以后的为 正则表达式中分组的内容,
以下面的代码为例, 因为有两个分组, 所以 b,c 分别保存 这两个分组所捕获到的内容,
然后接下来的参数代表 匹配成功时所在的位置, 然后再接下来是整个字符串, 然后就没有了(所以f是`undefined).

再感受一下:

再感受一下:


详细参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace

中描述那段里的第二段。
 


str.replace(reg,function($1,$2,$3)){
    //$1 为整个匹配你reg的字符串
    //$2-$n-1为匹配你reg要捕获的内容
}

你可以打印下对应参数

str.replace(reg,function()){
    console.log([].slice.call(arguments));
}

所以你的代码里b 就对应你正则里的\d+,就是你传入字符串里的0,1,2

【热门文章】
【热门文章】