| The code is as follows |
Copy Code |
Stringobject.replace (regexp/substr,replacement)
|
Replacement can be either a string or a function. If it is a string, then each match is replaced by a string. ECMAScript v3 stipulates that the parameter replacement of the replace () method can be a function rather than a string. In this case, each match calls the function, and the string it returns is used as the replacement text. The
first parameter of the function is a string that matches the pattern. The next argument is a string that matches the subexpression in the pattern, and can have 0 or more of these parameters. The next argument is an integer that declares where the match appears in the Stringobject. The last parameter is the stringobject itself.
Obviously, the argument between the second and last third of the replacement function is "a string that matches the subexpression in the pattern", which is determined by the number of the child expression.
Accordingly, we give two examples to compare the description:
Match mode is:/cj[0-9]{2}/g (no subexpression)
The replacement function has 3 parameters, respectively:
"0" "CJ90"
"1" 0
"2" "CJ9080"
| The code is as follows |
Copy Code |
function Replacestr (s) { function () { for (var i = 0, len = arguments.length i < len; i++) { Console.info ("Argument" + i + ":" + arguments[i]); } }); }; |
Run Result:
Match mode is:/((CJ) ([0-9]{2}))/g (with 3 subexpression: (Cj[0-9]{2}), (CJ), ([0-9]{2})
The replacement function has 6 parameters, respectively:
"0" "CJ90"
"1" "CJ90"
"2" "CJ"
"3" "90"
"4" 0
"5" "CJ9080"
| The code is as follows |
Copy Code |
function Replacestr (s) { function () { for (var i = 0, len = arguments.length i < len; i++) { Console.info ("Argument" + i + ":" + arguments[i]); } }); }; |
Run Result:
Obviously, the results of the two test examples are the same as expected. Note that when the replacement of the Replace function is a function, the arguments for this function are indeed as W3school said:
"0": a string matching the pattern;
"1-(length-3)": A string, 0 or more, that matches a subexpression in the pattern;
Length-2: Matches the string at the beginning of the index of the original string, starting at 0;
Length-1: The original string.