Created
July 27, 2013 14:40
-
-
Save popomore/6095041 to your computer and use it in GitHub Desktop.
string format
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
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); | |
}); | |
} | |
} |
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
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