Skip to content

Instantly share code, notes, and snippets.

@jmgunn87
Last active December 16, 2015 02:09
Show Gist options
  • Save jmgunn87/5359808 to your computer and use it in GitHub Desktop.
Save jmgunn87/5359808 to your computer and use it in GitHub Desktop.
printf for js
register = {
"beep": "boop"
};
function format(str) {
var argi = 0;
var args = arguments;
return str.replace(/(%\w{1}$)|(<.+>)/g,
function (match, specifier, interpol) {
if (specifier) {
var type = specifier.replace("%", "");
var arg = args[++argi];
switch (type) {
case 'd': return Number(arg);
case 'j': return JSON.stringify(arg);
}
return String(arg);
}
if (interpol) {
var key = interpol.replace(/<|>/g, "");
return register[key] || key;
}
});
}
console.log(format("%s", 1));
console.log(format("<beep> %s", 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment