Last active
November 22, 2019 08:42
-
-
Save FlameWolf/f88f062e31803e04874729e30b6a76cf to your computer and use it in GitHub Desktop.
String.prototype.format
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
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