Last active
July 4, 2019 10:16
-
-
Save vgerbase/d98663dd8b49dd3368f9e258de1a2529 to your computer and use it in GitHub Desktop.
JavaScript equivalent to printf/String.Format (https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/18234317#18234317)
This file contains hidden or 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: "Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Joe", adjective: "OK"});