Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.