[Solved] What does this javascript function do? Does it make sense? [closed]


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:

  1. We’re attaching a function named format to the native String object (note, not to instances of strings. For that, you’d use String.prototype).
  2. arguments is a special object that is part of a function’s execution context (which also includes things like the value of this). It is array-like (it has keys that range from 0 to arguments.length-1) but it is not an Array (it is not an instance of Array and therefore does not have any of its prototype methods, like pop or push). The arguments object is how a JavaScript function can take an arbitrary number of parameters.
  3. Loop through each argument…
  4. 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.
  5. Replace matches with the supplied value
  6.  
  7. Return the modified string.

solved What does this javascript function do? Does it make sense? [closed]