Created
February 6, 2013 04:27
-
-
Save comfuture/4720300 to your computer and use it in GitHub Desktop.
simple javascript implement of sprintf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sprintf(format, arr) { | |
var i = -1; | |
var replacer = function(exp, p0, p1, p2, p3, p4) { | |
if (exp == '%%') return '%'; | |
if (arr[++i] === undefined) return undefined; | |
var exp = p2 ? parseInt(p2.substr(1)) : undefined; | |
var base = p3 ? parseInt(p3.substr(1)) : undefined; | |
var val; | |
switch (p4) { | |
case 's': val = arr[i]; break; | |
case 'c': val = arr[i][0]; break; | |
case 'f': val = parseFloat(arr[i]).toFixed(exp); break; | |
case 'p': val = parseFloat(arr[i]).toPrecision(exp); break; | |
case 'e': val = parseFloat(arr[i]).toExponential(exp); break; | |
case 'x': val = parseInt(arr[i]).toString(base?base:16); break; | |
case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break; | |
} | |
val = typeof(val) == 'object' ? JSON.stringify(val) : val.toString(base); | |
var sz = parseInt(p1); /* padding size */ | |
var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */ | |
while (val.length<sz) val = p0 !== undefined ? val+ch : ch+val; /* isminus? */ | |
return val; | |
} | |
var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g; | |
return format.replace(regex, replacer); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment