JavaScript - Understanding the role of a variable in a function passed as an argument

I'm trying to work with regular expressions, in particular I've to shuffle the middle content of a string. I found an example that fits my needs Here and the answer I'm studying is the one by Brian Nickel.

This is the code proposed by Brian Nickel in the question:

myStr.replace(/\b([a-z])([a-z]+)([a-z])\b/ig, function(str, first, middle, last) {
return first +
       middle.split('').sort(function(){return Math.random()-0.5}).join('') + 
       last;
});

I'm very beginner in JavaScript and RegEx, I see here a function is passed as an argument, but I don't understand why there are four parameters, in particular I do not understand the first parameter str and why if I remove it, function doesn't work anymore correctly.

I now it's a silly question, but I don't found what I want on the Web, or maybe I don't know how to search properly. Thanks in advance

Answers


When using replace with RegExp, the function use as callback receive 1+n parameters where n are the match inside parenthesis.

The always come in that order :

  1. The complete matched string.
  2. The first parenthesis.
  3. The second parenthesis.
  4. Go on...

If you remove the str and the argument first become the matched string. So even if you don't use this argument, you need it!


Need Your Help

Why is my Node.js getting "program terminated" without an error

javascript node.js debugging segmentation-fault

I have a fairly large Node.js project that's been working great for an extensive period of development. Recently however -- and unfortunately cannot pinpoint exactly when it changed -- my applicati...