2 * sprintf and vsprintf for jQuery
3 * somewhat based on http://jan.moesen.nu/code/javascript/sprintf-and-printf-in-javascript/
5 * Copyright (c) 2008 Sabin Iacob (m0n5t3r) <iacobs@m0n5t3r.info>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * @license http://www.gnu.org/licenses/gpl.html
17 * @project jquery.sprintf
21 'b': function(val
) {return parseInt(val
, 10).toString(2);},
22 'c': function(val
) {return String
.fromCharCode(parseInt(val
, 10));},
23 'd': function(val
) {return parseInt(val
, 10);},
24 'u': function(val
) {return Math
.abs(val
);},
25 'f': function(val
, p
) {
27 val
= parseFloat(val
);
31 return p
&& val
.toFixed(p
) || val
;
33 'o': function(val
) {return parseInt(val
, 10).toString(8);},
34 's': function(val
) {return val
;},
35 'x': function(val
) {return ('' + parseInt(val
, 10).toString(16)).toLowerCase();},
36 'X': function(val
) {return ('' + parseInt(val
, 10).toString(16)).toUpperCase();}
39 var re
= /%(?:(\d+)?(?:\.(\d+))?|\(([^)]+)\))([%bcdufosxX])/g;
41 var dispatch = function(data
){
42 if(data
.length
== 1 && typeof data
[0] == 'object') { //python-style printf
44 return function(match
, w
, p
, lbl
, fmt
, off
, str
) {
45 return formats
[fmt
](data
[lbl
]);
47 } else { // regular, somewhat incomplete, printf
49 return function(match
, w
, p
, lbl
, fmt
, off
, str
) {
53 return formats
[fmt
](data
[idx
++], p
);
59 sprintf: function(format
) {
60 var argv
= Array
.apply(null, arguments
).slice(1);
61 return format
.replace(re
, dispatch(argv
));
63 vsprintf: function(format
, data
) {
64 return format
.replace(re
, dispatch(data
));