I saw what you were trying to achieve with string formatting. Instead of answering your initial question about how to proceed with a brief implementation of one part of it, I offer a brief (and more flexible) implementation for everything:
String.prototype.format = function () { var args = arguments; return this.replace(/\{(?:(\d+)|(\w+))\}/g, function (s, idx, prop) { return prop && args[0] ? args[0][prop] : args[idx]; }); };
When you have the number n inside the token "{n}" , it uses the nth argument to replace it. Otherwise, for non-numeric keys, it selects the corresponding property of the first argument.
For instance:
"I have {1} {name}s in my basket.".replace({ type: "fruit", name: "eggplant" }, 4);
Return:
"I have 4 eggplants in my basket."
source share