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, Josh
Going line by line:
- We’re attaching a function named
format
to the nativeString
object (note, not to instances of strings. For that, you’d useString.prototype
). arguments
is 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 from0
toarguments.length-1
) but it is not an Array (it is not an instance ofArray
and therefore does not have any of its prototype methods, likepop
orpush
). Thearguments
object is how a JavaScript function can take an arbitrary number of parameters.- Loop through each argument…
- Build a regular expression which matches
{
i}
where i is the loop iteration number. The second argument is the regex options,gm
enables global and multiline mode. - Replace matches with the supplied value
- Return the modified string.
solved What does this javascript function do? Does it make sense? [closed]