Skip to content

Instantly share code, notes, and snippets.

@theLine
Forked from ewjoachim/format.js
Last active Dec 30, 2015
Embed
What would you like to do?
/**
* 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