Skip to content

Instantly share code, notes, and snippets.

@ianpgall
Last active December 20, 2015 03:19
Show Gist options
  • Save ianpgall/6062595 to your computer and use it in GitHub Desktop.
Save ianpgall/6062595 to your computer and use it in GitHub Desktop.
JavaScript function to format strings with the format {#}
var Format = (function () {
"use strict";
var refToString, toString, re, slice, ret;
refToString = {}.toString;
toString = function (p) {
return refToString.call(p);
};
re = /\{(\d+)\}/g;
slice = function (args, start) {
var arr, i, j, cur;
start = start || 0;
arr = [];
for (i = start, j = args.length; i < j; i++) {
cur = args[i];
arr.push(cur);
}
return arr;
};
ret = function (str, args) {
if (toString(args) !== "[object Object]") {
args = slice(arguments, 1);
}
return str.replace(re, function (match, $1) {
var arg = args[$1];
return arg === undefined ? match : arg;
});
};
return ret;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment