简体   繁体   中英

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM