javascript - js的replace函数入参为function时的疑问
PHPz
PHPz 2017-04-10 16:07:38
[JavaScript讨论组]
(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为什么是"{}"里的内容

PHPz
PHPz

学习是最好的投资!

全部回复(2)
怪我咯

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

中描述那段里的第二段。
 

ringa_lee
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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号