String.prototype.format = function(args) { var result = this; if (arguments.length < 1) { return result; } var data = arguments; //如果模板参数是数组 if (arguments.length == 1 && typeof (args) == "object") { //如果模板参数是对象 data = args; } for (var key in data) { var value = data[key]; if (undefined != value) { result = result.replace("{" + key + "}", value); } } return result; }
//两种调用方式 var template1="我是{0},今年{1}了"; var result1=template1.format("loogn",22); var template2="我是{name},今年{age}了"; var result2=template2.format({name:"loogn",age:22}); //两个结果都是"我是loogn,今年22了"
参考:http://www.cnblogs.com/yelaiju/archive/2012/03/27/2419212.html
Javascript字符串的格式化,布布扣,bubuko.com
原文:http://my.oschina.net/looly/blog/301362