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 string after replacement.
Here only introduces the related operations of regular expressions. For other replacement operations, please refer toReplace() method of String object in javascriptOne article.
Syntax structure:
(regexp,replacement)
The parameter list is as follows:
Parameter name | Semantic explanation |
regexp | Required. RegExp object. |
replacement | Required. A string value. Specifies a function that replaces text or generates a replacement text. |
Example code:
<script> var str="I love jb51"; var reg=/j(?:\w)+1/; ((reg,"girls")); </script>
The above code can replace the substring in the string that can be matched by regular expressions with "girls".
Special Note:
replacement can be a string or a function. If it is a string, then each match will be replaced by the string.
The $ character in replacement can have a specific meaning, as shown in the following table:
character | Semantic explanation |
$1、$2、...、$9 | Text that matches the 1st to 9th subexpressions in regexp. |
$& | Substring matching regexp. |
$$ | Direct measurement symbol. |
$` | The text before lastMatch in the input string. |
$' | Text after lastMatch in the input string. |
If replacement is a function, please refer to the section on the parameters when the second parameter of JavaScript is a function.
Example code:
<script> var str="jb51,net"; var newStr=(/(\w+),(\w+)/,"$2 $1"); (newStr); </script>
Output:net jb51
Function function: The replace function returns the copy of the string after literal replacement according to the regular expression.
Function format: (rgExp, replaceText)
Parameters: string stringObj, rgExp regular expression, replaceText replaced content
The contents involved in this article include string creation, implicit creation of regular expressions, creating regular expressions, and matching the use of replace methods.
Sample code:
<html> <script language="javascript" type="text/javascript"> //The content of the string to be replacedvar objStr=new String("Designed By Androidyue"); //Implicitly create regular expression objectsvar reG=/e/w?/g;//Global match (g is a global match parameter), match e or e? contentvar re=/e/w?/;//No parameter specified, value matches oncewith(document){ write("String before matching"+objStr+"<br>"); write("Global matching string"+(reG,"**")+"<br>"); write("Make a match, no parameter value specified for one match"+(re,"××")); } </script> </html>
I will write a few articles about regular expressions. Of course, the best way is to try to write something yourself.