Regular expression replace () function:
This function replaces the substring in the string that matches the regular expression with the specified string.
The return value is a new, replaced string.
This only describes the actions of regular expressions, and other substitutions can refer to the text of the replace () method of a JavaScript string object.
Syntax structure:
Stringobject.replace (regexp,replacement)
The parameters list is as follows:
Parameter name |
Semantic interpretation |
Regexp |
Necessary. RegExp object. |
Replacement |
Necessary. A string value. Provides a function that replaces text or generates alternate text. |
Instance code:
<script>
var str= "I love jb51";
var reg=/j (?: \ W) +1/;
Console.log (Str.replace (Reg, "girls"));
</script>
The above code replaces the string with a substring that can be matched by a regular expression as "girls".
Special Note:
Replacement can be either a string or a function. If it is a string, then each match is replaced by a string.
The $ character in replacement can have a specific meaning, as shown in the following table:
Character |
Semantic interpretation |
$ 、...、 $ |
Text that matches the 1th to 9th subexpression in RegExp. |
$& |
The substring that matches the regexp. |
$$ |
The direct measure symbol. |
$` |
The text before lastmatch in the input string. |
$' |
The text after the lastmatch in the input string. |
If replacement is a function, you can refer to the chapter of the parameters in JavaScript () when the second parameter is a function.
Instance code:
<script>
var str= "jb51,net";
var newstr=str.replace (/(\w+), (\w+)/, "$ $");
Console.log (NEWSTR);
</script>
Output:net jb51
function function: The Replace function returns a copy of a string that is replaced with text based on a regular expression.
function format: Stringobj.replace (Rgexp, ReplaceText)
Parameters: string stringobj,rgexp Regular expression, ReplaceText replaced content
This article covers the creation of strings, regular expressions implicitly creating objects, creating regular expressions, and matching the use of the Replace method
Sample code:
About regular Expressions I will write a few articles, of course, the best way is to try to write something