在写js的时候,每每会碰到字符串拼接的问题,若是简单,直接使用+号链接字符串就能够了, 可是若是复杂,+用起来就很是不爽,在.net中有,Sting.Format函数,用起来仍是很爽的,因而就想着js中是否是有相似的函数,答案是没有,可是js能够扩展原型,因而在网上找到不少版本的format, 功能都比较简单,也挺实用。 通过我一些思考,改造,扩展了format函数的功能, 我的感受挺实用,代码也很是少,因此发出来共享下, 废话很少说,直接上码,代码不多,不解释。数组
String.prototype.format = function() { var args, ret = '', type = Object.prototype.toString.call(arguments[0]); if (type == "[object Object]") { args = arguments; } else if (type == "[object Array]") { type = Object.prototype.toString.call(arguments[0][0]); if (type == "[object Object]" || type == "[object Array]") { args = arguments[0]; } else { args = arguments; } } else { args = [arguments]; } for (var i in args) { var a = args[i]; ret += this.replace(/{([\w]+?)}/g, function(all, match) { return a[match]; }); } return ret; }
"{0}|{1}|{2}".format([2,3,4]); // 2|3|4 "{0}|{1}|{2}".format(["a","b","c"]); // a|b|c
"{0}|{1}|{2}".format(2,3,4); // 2|3|4 "{0}|{1}|{2}".format("a","b","c"); // a|b|c
"{0}|{1}|{2}".format([1,2,3],[4,5,6]); // 1|2|34|5|6
"<li value='{v}'>{n}</li>".format({v:1,n:'n1'},{v:2,n:'n2'}); // <li value="1">n1</li><li value="2">n2</li>
"{a}|{b}|{c}".format({a:1,b:"ef",c:23}); //1|ef|23
"{0}|{1}|{2}".format([[1,2,3],[4,5,6]]); // 1|2|34|5|6
"<li value='{v}'>{n}</li>".format([{v:1,n:'n1'},{v:2,n:'n2'}]); // <li value="1">n1</li><li value="2">n2</li>