在寫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>