Created
January 28, 2016 15:17
-
-
Save selahattinunlu/425459afcbeb22f6154c to your computer and use it in GitHub Desktop.
Javascript Printf - (String Template ES5)
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
/** | |
* Source: https://monocleglobe.wordpress.com/2010/01/12/everybody-needs-a-little-printf-in-their-javascript/ | |
* | |
* Example: | |
* "{f} {b}".printf({f: "foo", b: "bar"}); | |
* | |
* "%s %s".printf(["foo", "bar"]); | |
* | |
* "%s %s".printf("foo", "bar"); | |
* | |
* // all of which give this result: | |
* "foo bar" | |
*/ | |
String.prototype.printf = function (obj) { | |
var useArguments = false; | |
var _arguments = arguments; | |
var i = -1; | |
if (typeof _arguments[0] == "string") { | |
useArguments = true; | |
} | |
if (obj instanceof Array || useArguments) { | |
return this.replace(/\%s/g, | |
function (a, b) { | |
i++; | |
if (useArguments) { | |
if (typeof _arguments[i] == 'string') { | |
return _arguments[i]; | |
} | |
else { | |
throw new Error("Arguments element is an invalid type"); | |
} | |
} | |
return obj[i]; | |
}); | |
} | |
else { | |
return this.replace(/{([^{}]*)}/g, | |
function (a, b) { | |
var r = obj[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