1 String.prototype.format = function (args) { 2 var result = this; 3 if (arguments.length > 0) { 4 var reg; 5 if (arguments.length == 1 && typeof (args) == "object") { 6 for (var key in args) { 7 if (args[key] != undefined) { 8 reg = new RegExp("({" + key + "})", "g"); 9 result = result.replace(reg, args[key]); 10 } 11 } 12 } 13 else { 14 for (var i = 0; i < arguments.length; i++) { 15 if (arguments[i] != undefined) { 16 reg = new RegExp("({)" + i + "(})", "g"); 17 result = result.replace(reg, arguments[i]); 18 } 19 } 20 } 21 } 22 return result; 23 } 24 25 window.onload = function() { 26 var template1 = "我是{0},今年{1}了"; 27 var template2 = "我是{name},今年{age}了"; 28 var result1 = template1.format("loogn", 22); 29 var result2 = template2.format({ name: "loogn", age: 22 }); 30 };
来源:http://www.cnblogs.com/loogn/archive/2011/06/20/2085165.html