About definitions
The replace () method is used to replace other characters with some characters in a string, or to replace a substring that matches a regular expression.
About syntax
Stringobject.replace (regexp/substr,replacement)
About parameters
| Parameters |
Describe |
Regexp/substr |
Necessary. A RegExp object that specifies the substring or pattern to replace. Note that if the value is a string, it is used as the direct volume text pattern to be retrieved, instead of being converted to the RegExp object first. |
| Replacement |
Necessary. A string value. A function that specifies replacement text or generates alternate text. |
1, the first parameter regexp/substr, using the regular expression with the global identifier G, you can replace all matching substrings, otherwise it will only match once.
For example:
var str = "AAAAA"; var str1 = str.replace ("A", "B");
var str2 = str.replace (/a/g, "B");
operation Result: str1, "baaaa", str2, "BBBBB"
2. The second parameter, replacement, can be a string or function, or it can be a specific meaning that the $ character has.
| character |
Replace text |
| $, $ 、...、 |
The text that matches the 1th to 99th sub-expression in RegExp. |
| $& |
A substring that matches the regexp. |
| $` |
The text that is located to the left of the matching substring. |
| $ |
The text on the right side of the matching substring. |
| $$ |
Direct volume symbol. |
A. examples of function:
var str = "111222AA"; str.replace (function(word) { return "B";});
Run Result: "Bbaa"
Example of B. $
var str = "1234567890"/(\d{3}) (\d{3}) (\d{4})/g, "$1-$2-$3");
Operation Result: "123-456-7890"
Note: Most of the time, the combination of regexp and $ is used to achieve demand, so it is necessary to know some basic regular expression rules.
Some usage summaries of replace () in JavaScript