JavaScript/代码技巧/拼接字符串

来自康健生活

占位符拼接字符串

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("\\{" + i + "\\}", "g"), arguments[i]);
        return s;
    }
}
 
var str = "{one}{two}{three}".format({one: "1",two: "2",three: "3"}); //123
var str2 = "{0} {1} {2}".format("how","are","you"); //how are you