Skip to content

Instantly share code, notes, and snippets.

@theLine
Forked from ewjoachim/format.js
Last active December 30, 2015 02:59
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 theLine/7766456 to your computer and use it in GitHub Desktop.
Save theLine/7766456 to your computer and use it in GitHub Desktop.
/**
* Does the same as a simple form of python "".format
* that will not work for anything else than number or string.
* Array form :
* "I have {} replacements to {}".format("two", "make")
* "I have {} replacements to {}".format(["two", "make"])
* "I have {0} replacements to {1}".format(["two", "make"])
* Dict form :
* "Hello {name} !".format({name: "Bob"});
* "I am {age} years old".format({age: 12});
* "Pi is {pi} ! ".format({"pi": Math.PI});
* No error is outputted in case of malformed input. It just isn't replaced.
**/
String.prototype.format = function (obj) {
var source = (typeof obj === 'object') ? obj : arguments,
i = 0
;
return this.replace(/{([^{}]*)}/g, function (a, b) {
if (b === "") {
b = i++;
}
var r = source[b];
return (typeof r === 'string' || typeof r === 'number') ? r : a;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment