Python's.format for Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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