Created
October 17, 2013 09:31
-
-
Save antelle/7021916 to your computer and use it in GitHub Desktop.
Javascript simple string formatting function
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
// "{} {}".format("a", "b") => "a b" | |
// "{1} {0}".format("a", "b") => "b a" | |
// "{foo} {bar}".format({ foo: "a", bar: "b" }) => "a b" | |
String.prototype.format = function() { | |
var args = arguments; | |
var argNum = 0; | |
return this.replace(/\{(\w*)\}/gi, function(match) { | |
var curArgNum, prop = null; | |
if (match == "{}") { | |
curArgNum = argNum; | |
argNum++; | |
} else { | |
curArgNum = match.substr(1, match.length - 2); | |
var parsed = ~~curArgNum; | |
if (parsed.toString() === curArgNum) { | |
curArgNum = parsed; | |
} else { | |
prop = curArgNum; | |
curArgNum = 0; | |
} | |
} | |
var result = curArgNum >= args.length ? "" : prop ? args[curArgNum][prop] || "" : args[curArgNum]; | |
return result; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment