lcgyh / myDocs

0 stars 0 forks source link

js format用法 #47

Open lcgyh opened 6 years ago

lcgyh commented 6 years ago
var code='123'
    var frstcode='ph001'
    var aftercode='ph002'
    var str='修改商品编码%s由%s改为%s'

    String.prototype.format = function() {  
        if(arguments.length == 0) return this;  
        var param = arguments[0];  
        var s = this;  
        if(typeof(param) == 'object') {  
        for(var key in param)  
            s = s.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);  
            return s;  
        } else {  
            for(var i = 0; i < arguments.length; i++){
                s = s.replace(new RegExp("%s"), arguments[i]); 
            }  
            return s;  
        }  
    }

    var str1=str.format(code,frstcode,aftercode)
    console.log(str1)   //修改商品编码123由ph001改为ph002