Skip to content

Instantly share code, notes, and snippets.

@antelle
Created October 17, 2013 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antelle/7021916 to your computer and use it in GitHub Desktop.
Save antelle/7021916 to your computer and use it in GitHub Desktop.
Javascript simple string formatting function
// "{} {}".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