Last active
November 30, 2018 02:37
-
-
Save timhobbs/bb8a304a8d008d74fd29 to your computer and use it in GitHub Desktop.
C# style String.Format for JS
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
/* Examples: | |
* var test = "test {0} {1}, {2} - {0} {1} {2}".format('a', 'b', 'c'); | |
* var test2 = "the {0} ate the {1}".format("cat", "canary"); | |
*/ | |
String.prototype.format = function () { | |
var self = this; | |
var re = /\{\d+\}/g; | |
var m = self.match(re); | |
var indexes = []; | |
var mre = /[^\d+]/g; | |
for (var i = 0; i < m.length; i++) { | |
var idx = m[i].replace(mre, "") * 1; | |
if (indexes.indexOf(idx) === -1) { | |
indexes.push(idx); | |
} | |
} | |
if (arguments.length <= m.length) { | |
for (var i = 0; i < indexes.length; i++) { | |
var t = indexes[i]; | |
var tre = new RegExp("\\{" + t + "\\}", "g"); | |
self = self.replace(tre, arguments[t] || ""); | |
} | |
} else { | |
throw new Error("Invalid argument(s)"); | |
} | |
return self.valueOf(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment