Home >Web Front-end >JS Tutorial >JavaScript String.replace function parameter example description_Basic knowledge

JavaScript String.replace function parameter example description_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:32:281048browse

Email:longsu2010 at yeah dot net
The function signature of the replace function of js String is as follows:
replace(match/* string OR regular expression*/, replacement/* string OR function*/)
The function is to replace the match in the string with replacement and return the replaced string.
If the first parameter is a string, there is nothing to say, but remember that the match (first) function is executed only once when the string is replaced.

So the first parameter is usually a regular expression, for example:
replace(/a/g, "b") // Replace all a's in the string with b.

The second parameter can be a string, which can contain the grouping of the regular expression of the first parameter, for example:
replace(/(a){2,2}/g, "$1b") // Replace all aa in the string with ab.

If the second parameter is a function, what are the parameters of the function? For example:

Copy code The code is as follows:

"bbabc".replace(/(a )(b)/g, function(){
console.log(arguments)
});

The parameters will be:
1 , the characters matched by the entire regular expression.
2. The content matched by the first group, the matched content of the second group... and so on until the last group.
3. The subscript (position) of this match in the source string.
4. Derived from the string
, so the output of the example is

["ab", "a", "b", 2, "bbabc"]

Second The return value of the parameter will be replaced in the source string, because if the js function has no return value, calling the function will result in undefined, so if the second parameter has no return value, undefined will be replaced in the source string.
If the first parameter is a string and the second parameter is a function, then treat it as the first parameter is a regular expression without grouping, so that the parameters of the second parameter can be determined.
There are some inappropriate expressions in the article, such as "replacement into the source string" (the source string only acts as a template and does not really change, the string is an immutable variable), I hope it will not Misleading everyone.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn