Skip to content

Instantly share code, notes, and snippets.

@popomore
Created July 27, 2013 14:40
Show Gist options
  • Save popomore/6095041 to your computer and use it in GitHub Desktop.
Save popomore/6095041 to your computer and use it in GitHub Desktop.
string format
function format(fmt, args) {
if (!fmt) return '';
var toString = Object.prototype.toString;
if (toString.call(args) === '[object Object]') {
return fmt.replace(/%{?([a-z]*)}?/g, function(all, m1){
return args[m1] ? args[m1] : all;
});
} else {
if (toString.call(args) !== '[object Array]') {
args = Array.prototype.slice.call(arguments, 1);
}
return fmt.replace(/%([sd])/g, function(all, m1){
if (!args.length) return all;
var arg = args.shift();
return m1 === 's' ? String(arg) : Number(arg);
});
}
}
assert(format('a%s:%s', 's'), 'as:%s');
assert(format('a%s:%s', 's', 'd', 't'), 'as:d');
assert(format('a%s:%s', ['s', 'd', 't']), 'as:d');
assert(format('a%s', 1), 'a1');
assert(format('a%d', '3d'), 'aNaN');
assert(format('a%q', 's'), 'a%q');
assert(format('a%{a}b%b%a', {a:1, b:2}), 'a1b21');
function assert(expect, truth) {
console.log(expect === truth);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment