Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Last active November 22, 2019 08:42
Show Gist options
  • Save FlameWolf/f88f062e31803e04874729e30b6a76cf to your computer and use it in GitHub Desktop.
Save FlameWolf/f88f062e31803e04874729e30b6a76cf to your computer and use it in GitHub Desktop.
String.prototype.format
Object.defineProperty(String.prototype, "format", {
"value": function(...args) {
const replacer = function(match, index) {
return (args[parseInt(index)] || "");
};
return this.replace(/\${(\d*?)\}/g, replacer);
}
});
/***********************************************************************************************************/
/********************************************** Usage **********************************************/
/***********************************************************************************************************/
"${0} ${1} ${2}!".format("This", "is", "Sparta"); // Output: This is Sparta!
"${0} ${1} ${0}!".format("This", "is", "Sparta"); // Output: This is This!
"${0} ${1} ${2}!".format("This", "is"); // Output: This is !
"${0} ${1} ${2}!".format("This", "is", "Sparta", "Woo"); // Output: This is Sparta!
"${0} ${1} ${3}!".format("This", "is", "Sparta"); // Output: This is !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment