1. Replacement of JS strings and use of the replace () method
The replace (regexp, replacement) method has two parameters. The first parameter can be a plain text string or a RegExp object. For details, see the use of the RegExp object; the second parameter can be a string or a function.
The following is an example of JS string replacement:
Example 1:
Copy codeThe Code is as follows:
Var str = "Hello world! ";
Document. write (str. replace (/world/, "phper "));
Example 2:
Copy codeThe Code is as follows:
Var reg = new RegExp ("(\ w +), (\ d +), (\ w +)", "gmi ");
Var info = "Lili, 14, China ";
Var rep = info. replace (reg, "She is $1, $2 years old, come from $3 ");
Alert (rep );
Example 3:
Copy codeThe Code is as follows:
Var reg = new RegExp ("(\ w +), (\ d +), (\ w +)", "gmi ");
Var info = "Lili, 14, China ";
Var name, age, from;
Function prase_info (m, p1, p2, p3) {// you can also use a non-explicit parameter, obtained using arguments
Name = p1;
Age = p2;
From = p3;
Return "She is" + p1 + "," + p2 + "years old, come from" + p3;
}
Var rep = info. replace (reg, prase_info );
Alert (rep );
Aler (name );
2. Use of RegExp objects
JavaScript provides a RegExp object to perform operations and functions on regular expressions. Each regular expression pattern corresponds to a RegExp instance. You can create an instance of the RegExp object in two ways.
Use RegExp's explicit constructor Syntax: new RegExp ("pattern" [, "flags"]); Use RegExp's implicit constructor in plain text format: /pattern/[flags]. In Example 4, the two statements are equivalent.
Example 4:
Copy codeThe Code is as follows:
Var re1 = new RegExp ("\ d {5 }");
Var re2 =/\ d {5 }/;
3. string search and use of the exec () method
The exec () method returns an array containing matching results. If no match is found, the return value is null.
Example 5:
Copy codeThe Code is as follows:
Var reg = new RegExp ("(\ w +), (\ d +), (\ w +)", "gmi ");
Var m1_reg.exe c ("Lili, 14, China ");
Var s = "";
For (I = 0; I <m. length; I ++ ){
S = s + m [I] + "\ n ";
}
Alert (s );
4. Use of the test () method
RegExpObject. test (string)
If the string contains the text that matches RegExpObject, true is returned; otherwise, false is returned.
Example 6:
Copy codeThe Code is as follows:
Var reg = new RegExp ("(\ w +), (\ d +), (\ w +)", "gmi ");
Var m = reg. test ("Lili, 14, China ");
Alert (RegExp. $1 );
Alert (RegExp. $2 );
Alert (RegExp. $3 );