Created
February 18, 2015 16:02
-
-
Save krmgns/fad3983f39f5a5530943 to your computer and use it in GitHub Desktop.
Simple string formatter with integer and float operators.
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.format = function() { | |
| var string = this.toString(); | |
| if (arguments.length) { | |
| var tokens = string.match(/%([sdf])/g) || [], | |
| token, i = 0, replace; | |
| while (token = tokens.shift()) { | |
| replace = arguments[i++]; | |
| switch (token) { | |
| case "%d": | |
| string = string.replace(token, parseInt(replace, 10) || 0); | |
| break; | |
| case "%f": | |
| string = string.replace(token, parseFloat(replace) || 0); | |
| break; | |
| default: | |
| string = string.replace(token, replace); | |
| } | |
| } | |
| } | |
| return string; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment