javascript sprintf方法

转载自: http://demon.tw/programming/javascript-sprintf.html

 1 function str_repeat(i, m) {
 2     for (var o = []; m > 0; o[--m] = i);
 3     return o.join('');
 4 }
 5 function sprintf() {
 6     var i = 0, a, f = arguments[i++], o = [], m, p, c, x, s = '';
 7     while (f) {
 8         if (m = /^[^x25]+/.exec(f)) {
 9             o.push(m[0]);
10         }
11         else if (m = /^x25{2}/.exec(f)) {
12             o.push('%');
13         }
14         else if (m = /^x25(?:(d+)$)?(+)?(0|'[^$])?(-)?(d+)?(?:.(d+))?([b-fosuxX])/.exec(f)) {
15             if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) {
16                 throw('Too few arguments.');
17             }
18             if (/[^s]/.test(m[7]) && (typeof(a) != 'number')) {
19                 throw('Expecting number but found ' + typeof(a));
20             }
21             switch (m[7]) {
22                 case 'b': a = a.toString(2); break;
23                 case 'c': a = String.fromCharCode(a); break;
24                 case 'd': a = parseInt(a); break;
25                 case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
26                 case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
27                 case 'o': a = a.toString(8); break;
28                 case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
29                 case 'u': a = Math.abs(a); break;
30                 case 'x': a = a.toString(16); break;
31                 case 'X': a = a.toString(16).toUpperCase(); break;
32             }
33             a = (/[def]/.test(m[7]) && m[2] && a >= 0 ? '+'+ a : a);
34             c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
35             x = m[5] - String(a).length - s.length;
36             p = m[5] ? str_repeat(c, x) : '';
37             o.push(s + (m[4] ? a + p : p + a));
38         }
39         else {
40             throw('Huh ?!');
41         }
42         f = f.substring(m[0].length);
43     }
44     return o.join('');
45 }
原文地址:https://www.cnblogs.com/eecjimmy/p/4938607.html