Last active
December 16, 2015 02:09
-
-
Save jmgunn87/5359808 to your computer and use it in GitHub Desktop.
printf for js
This file contains 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
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