Skip to content

Instantly share code, notes, and snippets.

@ando19721226
Created August 9, 2012 03:20
Show Gist options
  • Save ando19721226/3300627 to your computer and use it in GitHub Desktop.
Save ando19721226/3300627 to your computer and use it in GitHub Desktop.
sprintf
var sprintf = function (str) {
var args = Array.prototype.slice.call(arguments, 1),
hash = {
'%s': String,
'%d': parseInt,
'%f': parseFloat
};
return str.replace(/%0(\d+)d/g, function (m, num) {
var r = String(args.shift()),
c = '';
num = parseInt(num, 10) - r.length;
while ((num -= 1) >= 0) {
c += '0';
}
return c + r;
}).replace(/%[sdf]/g, function (m) {
return hash[m](args.shift());
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment