email:longsu2010 at yeah Dot net
The function signature for the Replace function of the JS string is as follows:
Replace (match/* string or regular expression * */, replacement/* string or function * *)
The effect is to replace match from a string with replacement and return the replacement string.
If the first argument is a string, there is nothing to say, but remember to do so only if the match (first time) function is replaced once from the character string.
So the first parameter is usually a regular expression, for example:
Replace (/a/g, "B")//Replaces all a from a string with B.
The second argument can be a string that can contain a grouping of the first argument regular expression, for example:
Replace (/(a) {2,2}/g, "$1b")//Replaces all AA from the string with AB.
If the second parameter is a function, then what is the parameter of the function? Examples are as follows:
Copy Code code as follows:
"Bbabc". Replace (/(a) (b)/g, function () {
Console.log (arguments)
});
the parameters will be:
1. The entire regular expression matches the character.
2, the first packet matching content, the second packet matching content ... And so on until the last group.
3. This match is in the subscript (position) from the string.
4, from the string
So the output of the example is
["AB", "a", "B", 2, "BBABC"]
The return value of the second parameter will be replaced with the originating string, because if the JS function has no return value, the call function will get undefined, so if the second parameter has no return value undefined will be replaced to the originating string.
If the first argument is a string, and the second argument is a function, then the first argument is a regular expression without grouping so that you can determine the parameters of the second parameter.
There are some improper representations in this article, such as "replace to originate in string" (the character that originates from the string just acts as a template, does not really change, the string is an immutable variable), hopefully not misleading.