The parameter descriptions of the callback function are also accurate:
The first parameter is the matched string, the last parameter is the original string, and the last parameter is the start position of the matched string index.
But I'm curious, what are the parameters between the second and the last three? In fact, W3school has provided the answer:
Copy codeThe Code is as follows:
The replace () method is used to replace other characters with some characters in a string, or replace a substring that matches a regular expression. Its syntax is:
StringObject. replace (regexp/substr, replacement)
Replacement can be a string or a function. If it is a string, each match will be replaced by a string.
ECMAScript v3 stipulates that the replacement parameter of the replace () method can be a function rather than a string. In this case, this function is called for each match.
It returns the string used as the replacement text. The first parameter of this function is a matching string. The following parameters match the subexpression in the pattern.
String, which can contain 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringObject. Last Parameter
Is stringObject itself.
Obviously, the parameter between the second and the third to the last of the replacement function is "a string matching the subexpression in the pattern". The specific number depends on the number of subexpressions.
Here, we will give two examples for comparison:
Example 1:
String: "CJ9080"
Matching mode:/CJ [0-9] {2}/g (no subexpression)
Expected results:
The replacement function has three parameters:
[0] "CJ90"
[1] 0
[2] "CJ9080"
Test code:
Copy codeThe Code is as follows:
Function replaceStr (s ){
Return s. replace (/CJ [0-9] {2}/g,
Function (){
For (var I = 0, len = arguments. length; I <len; I ++ ){
Console.info ("Argument" + I + ":" + arguments [I]);
}
});
};
Running result:
Example 2:
String: "CJ9080"
The matching mode is/(CJ) ([0-9] {2})/g (three subexpressions are available: (CJ [0-9] {2 }), (CJ), ([0-9] {2 }))
Expected results:
The replacement function has six parameters:
[0] "CJ90"
[1] "CJ90"
[2] "CJ"
[3] "90"
[4] 0
[5] "CJ9080"
Test code:
Copy codeThe Code is as follows:
Function replaceStr (s ){
Return s. replace (/(CJ) ([0-9] {2})/g,
Function (){
For (var I = 0, len = arguments. length; I <len; I ++ ){
Console.info ("Argument" + I + ":" + arguments [I]);
}
});
};
Running result:
Obviously, the results of both test examples are consistent with expectations. Note: When the replacement of the replace function is a function, the parameters of this function are as described in W3school:
[0]: A matching string;
[1-(length-3)]: The string that matches the subexpression in the pattern. There are 0 or more strings;
[Length-2]: the starting position of the index of the original string, starting from 0;
[Length-1]: The original string.