JavaScript系列 -> 字符串方法 replace 的第二个参数为函数

发布时间 2023-03-29 16:42:55作者: 77工作室

本篇文章要介绍,当字符串的replace方法第二个参数为函数的使用。

示例代码:

function fn(str){
    this.str = str;
}

fn.prototype.format = function() {
    var arg = arguments;
    return this.str.replace( /{(\d+)}/g, function(a,b){
        console.log('a:',a); 
        console.log('arg:',arg);
        console.log('b:',b);
        return arg[b] || '';
    })
}

调用:

var str = '<p>test{0}/{1}/{2}</p>';
var aa = new fn(str);
aa.format('12313','hello','world'); // 输出:'<p>test12313/hello/world</p>'

输出:
image

【注】 这个方法的目的是: 改写format方法,用传进去的参数替换在字符串中的{0},然后返回格式化或替换后的结果。

参考链接:

https://www.jb51.net/article/22614.htm (有启发?)