String.format = function()
{ var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++)
{ var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
Please explain. Thanks.
It takes the first argument as a format string and replaces instances of
{0}with the second argument,{1}with the third, and so on.String.format('{0} there, {1}', 'Hi', 'Josh');=>Hi there, JoshGoing line by line:
formatto the nativeStringobject (note, not to instances of strings. For that, you’d useString.prototype).argumentsis a special object that is part of a function’s execution context (which also includes things like the value ofthis). It is array-like (it has keys that range from0toarguments.length-1) but it is not an Array (it is not an instance ofArrayand therefore does not have any of its prototype methods, likepoporpush). Theargumentsobject is how a JavaScript function can take an arbitrary number of parameters.{i}where i is the loop iteration number. The second argument is the regex options,gmenables global and multiline mode.