早睡早起,方能养生
Sleep early rise early, way to keep healthy

js自定义format函数,js报错 str.format is not a function

super
2023-03-14 08:55
views 1523

js自定义format函数

 

let original_str = `你好呀,{name}!`;

let new_str = original_str.format({name: 'super'});
console.log(new_str); // 报错

 

 

提示format方法不存在,自定义format方法

 

String.prototype.format = function() {
    let obj = arguments[0];
    var str = this;
    $.each(obj, function (k,v) {
        var reg = new RegExp("\\{" + k + "\\}", "gm");
        str = str.replace(reg, v);
    });
    return str;
}

let original_str = `你好呀,{name}!`;
let new_str = original_str.format({name: 'super'});
console.log(new_str); // 你好呀,super!

 



分享
0 条讨论
top