0

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

Community
  • 1
  • 1
alessandrob
  • 1,605
  • 4
  • 20
  • 23
  • 1
    See the documentation, the function is explained for example here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Roman Hocke Mar 06 '14 at 13:22

1 Answers1

2

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!

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75