Skip to content

Instantly share code, notes, and snippets.

@marcoslhc
Forked from ando19721226/sprintf.js
Created May 9, 2016 19:29
Show Gist options
  • Save marcoslhc/a5421e03b5dc98197f863f1e3d28ecb3 to your computer and use it in GitHub Desktop.
Save marcoslhc/a5421e03b5dc98197f863f1e3d28ecb3 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