Skip to content

Instantly share code, notes, and snippets.

@timhobbs
Last active November 30, 2018 02:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timhobbs/bb8a304a8d008d74fd29 to your computer and use it in GitHub Desktop.
Save timhobbs/bb8a304a8d008d74fd29 to your computer and use it in GitHub Desktop.
C# style String.Format for JS
/* 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