Skip to content

Instantly share code, notes, and snippets.

@ewjoachim
Last active Dec 29, 2015
Embed
What would you like to do?
Python's.format for Javascript
String.prototype.format = function (obj) {
/**
* 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 outputed in case of malformed input. It just isn't replaced.
**/
var source;
if (typeof obj !== "object")
{
source = arguments;
} else {
source = obj;
}
var 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