samba
12/7/2012 - 7:29 PM

Simple Javascript String Formatter

Simple Javascript String Formatter

// 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;
  });
}

// 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)] })}