js中仿C#中的string.format功能
String.prototype.format = function (args) { var formatted = this; if (arguments.length > 0) { if (arguments.length == 1 && typeof args == "object") { for (var key in args) { if (args[key] != undefined) { var reg = new RegExp("({" + key + "})", "g"); formatted = formatted.replace(reg, args[key]); } } } else { for (var i = 0; i < arguments.length; i++) { if (arguments[i] != undefined) { var reg = new RegExp("({)" + i + "(})", "g"); formatted = formatted.replace(reg, arguments[i]); } } } } return formatted; }
"我是{0},性别{1}".format("张三","男") // 我是张三,性别男 "我是{name},性别{sex}".format({name:"李四",sex:"女"}) // 我是李四,性别女