The replace () method is used to replace other characters with some characters in a string, or replace a substring that matches a regular expression. The parameter description of the stringObject. replace (regexp, replacement) syntax is required. Specifies the RegExp object of the pattern to be replaced. Note that if the value is a string, it is used as the string to be retrieved.
The replace () method is used to replace other characters with some characters in a string, or replace a substring that matches a regular expression. The parameter description of the stringObject. replace (regexp, replacement) syntax is required. Specifies the RegExp object of the pattern to be replaced. Note that if the value is a string, it is used as the string to be retrieved.
The replace () method is used to replace other characters with some characters in a string, or replace a substring that matches a regular expression.
Syntax
stringObject.replace(regexp,replacement)
| Parameters |
Description |
| Regexp |
Required. Specifies the RegExp object of the pattern to be replaced. Note that if the value is a string, it is used as the direct text mode to be retrieved, rather than being converted to a RegExp object first. |
| Replacement |
Required. A string value. Specifies the function for replacing text or generating replacement text. |
Return Value
A new string is obtained after the first match of regexp or all matches are replaced by replacement.
Description
The replace () method of the string stringObject performs the search and replace operation. It searches stringObject for substrings that match regexp and replaces them with replacement. If regexp has a global flag, the replace () method replaces all matched substrings. Otherwise, it only replaces the first matched substring.
Replacement can be a string or a function. If it is a string, no matching will be replaced by the string. However, the $ character in replacement has a specific meaning. As shown in the following table, it indicates that the string obtained from pattern matching will be used for replacement.
| Character |
Replace text |
| $1, $2,..., $99 |
Text that matches the 1st to 99th subexpressions in regexp. |
| $ & |
The substring that matches the regexp. |
| $' |
Text on the left of the matched substring. |
| $' |
Text on the right of the matched substring. |
| $ |
Directly count the symbols. |
Note: ECMAScript v3 stipulates that the replacement parameter of the replace () method can be a function rather than a string. In this case, each match calls this function, and the string it returns will be used as the replacement text. The first parameter of this function is a matching string. The following parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringObject. The last parameter is stringObject itself.