Created
September 17, 2018 13:53
-
-
Save richardblondet/9a23a155e6a784f1ff2cbd8d84accd72 to your computer and use it in GitHub Desktop.
Stack Overflow own formatting function for the String prototype called formatUnicorn. Seen {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-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
String.prototype.formatUnicorn = String.prototype.formatUnicorn || function () { | |
"use strict"; | |
var str = this.toString(); | |
if (arguments.length) { | |
var t = typeof arguments[0]; | |
var key; | |
var args = ("string" === t || "number" === t) ? | |
Array.prototype.slice.call(arguments) | |
: arguments[0]; | |
for (key in args) { | |
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]); | |
} | |
} | |
return str; | |
}; | |
// Usage: | |
// "Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"}); // Hello, Gabriel, are you feeling OK? | |
// "a-{0}-bcd_{1}_ef".formatUnicorn("foo", "bar"); // yields "a-foo-bcd_bar_ef" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment