String.prototype.format = function (args) {
var result = this;
if (arguments.length > 0) {
var reg;
if (arguments.length == 1 && typeof (args) == "object") {
for (var key in args) {
if (args[key] != undefined) {
reg = new RegExp("({" + key + "})", "g");
result = result.replace(reg, args[key]);
}
}
}
else {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] != undefined) {
reg = new RegExp("({)" + i + "(})", "g");
result = result.replace(reg, arguments[i]);
}
}
}
}
return result;
} window.onload = function() {
var template1 = "我是{0},今年{1}了";
var template2 = "我是{name},今年{age}了";
var result1 = template1.format("loogn", 22);
var result2 = template2.format({ name: "loogn", age: 22 });
};

来源:http://www.cnblogs.com/loogn/archive/2011/06/20/2085165.html

04-15 11:16
查看更多