Last active
October 13, 2015 18:08
-
-
Save samba/4235805 to your computer and use it in GitHub Desktop.
Simple Javascript String Formatter
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
// This one only supports the '{0}' syntax for now... | |
function _format(p){var x = arguments;return p.replace(/\{([0-9]+)\}/g, function($0,n){ return x[1+Number(n)] })} |
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
// EXTREMELY simple format string handler. | |
// Examples: | |
// _format('this {1} is {0}!', 'amazing', 'pizza') => "this pizza is amazing!" | |
// _format('one %s two %d four', 'five', 3) => "one five two 3 four" | |
function _format(pattern){ | |
var vals = arguments, count = 1, q = parseInt; | |
return pattern.replace(/\{([0-9]+)\}|%([sd])/g, function($0, num, type){ | |
var val_str = type ? (vals[count++]) : (num ? vals[q(num) + 1] : ''); | |
if(type == 'd') val_str = q(val_str); | |
return val_str; | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment