Skip to content

Instantly share code, notes, and snippets.

@samba
Last active October 13, 2015 18:08
Show Gist options
  • Save samba/4235805 to your computer and use it in GitHub Desktop.
Save samba/4235805 to your computer and use it in GitHub Desktop.
Simple Javascript String Formatter
// 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)] })}
// 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