Skip to content

Instantly share code, notes, and snippets.

@ewjoachim
Last active December 29, 2015 17:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ewjoachim/7702805 to your computer and use it in GitHub Desktop.
Save ewjoachim/7702805 to your computer and use it in GitHub Desktop.
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