String.prototype.format2 = function (args) {var s = this, Vals = [], rst = [], pattern =/({|}) /g, Reg = S.match (pattern), Matchs = S.match (/({+[-\w]+}+)/g); if (matchs! = null) {if (Arguments.length > 1) {for (var i = 0, c = arguments.length; i < C; i++ {if (arguments[i]! = undefined) {Vals.push (arguments[i]); }}}} else if (Object.prototype.toString.call (args) = = = ' [Object Array] ') {vals = args; } else if (args! = undefined && args! = null) {Vals.push (args); } var len = vals.length; for (var i = 0, c = matchs.length; i < C; i++) {var _t = matchs[i], _tv = _t.replace (Pattern, '), _r = _t. Match (pattern); if (_r.length% 2! = 0 | |!/^[0-9]+$/.test (_TV)) {throw new Error (' Input string is not formatted correctly. ‘); } var idx = parseint (_TV, 10); if (idx >= len) {The throw new Error (' zero-based ' index must be greater than or equal to zero and is less than the size of the parameter list. ‘); } var _p = S.indexof (_t), _c = _t.match (/{/g). Length, _v = Vals[idx]; if (_v = = null) {throw new Error (' value cannot be null. ‘); } var _t1 = _t.replace (/{{/g, ' {'). Replace (/}}/g, '} '); Rst.push (s.substr (0, _p) + (_c > 1?) (_c% 2! = 0? _t1.replace (' {' + idx + '} ', _v): _T1): _v)); s = s.substr (_p + _t.length); } rst.push (s); Return Rst.join ("); } else if (reg! = null && reg.length > 0) {throw new Error (' the input string is not formatted correctly. ‘); } return s;};
Only basic functionality is implemented
Examples are as follows:
var str = ' (X{{{{0}}} {1}) {2} & X{0} {3} {4}_{5} * (X{0} + {6}) ';
Console.log (STR.FORMAT2 ([7, ' >= ', 123, ' < ', 123, ' K ', ' B ']));
var str = ' Hello: {0}, this is a pseudo C # {1} function written with {0} ';
Console.log (STR.FORMAT2 ([' JS ', ' format ']);
Console.log (STR.FORMAT2 (' JS ', ' format '));
Operation Result:
String.Format function of JS imitating C #