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(‘输入字符串的格式不正确。‘); } var idx = parseInt(_tv, 10); if (idx >= len) { throw new Error(‘索引(从零开始)必须大于或等于零,且小于参数列表的大小。‘); } var _p = s.indexOf(_t), _c = _t.match(/{/g).length, _v = vals[idx]; if (_v == null) { throw new Error(‘值不能为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(‘输入字符串的格式不正确。‘); } return s; };
仅实现了基本的功能
示例如下:
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 = ‘你好:{0},这是用{0}写的一个仿C#的{1}函数‘;
console.log(str.format2([‘JS‘,‘format‘]));
console.log(str.format2(‘JS‘,‘format‘));
运行结果:
时间: 2024-10-10 19:36:26