1, the substitution of JS string and the use of replace () method
The Replace (Regexp,replacement) method has two parameters, the first parameter can be a plain text string or a RegExp object, see the use of RegExp object, the second parameter is a string can also be a function.
The following is an example of JS string substitution:
Example 1:
var str= "Hello world!"; document.write (Str.replace (/world/, "Phper"));
Example 2:
var reg=new RegExp ("(\\w+), (\\d+), (\\w+)", "GMI"), var info= "Lili,14,china"; var rep=info.replace (Reg, "She is $ $, $ Years old, come from $ "); alert (rep);
Example 3:
var reg=new RegExp ("(\\w+), (\\d+), (\\w+)", "GMI"), var info= "Lili,14,china"; var name, age, From;function Prase_info (M, P1,P2,P3) {//can also use arguments to get name = P1 with non-explicit parameters; 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 complete the operation and functionality of the regular expression, and each regular expression pattern corresponds to a regexp instance. There are two ways to create an instance of a RegExp object.
Using RegExp's explicit constructor, the syntax is: New REGEXP ("pattern" [, "Flags"]), using the implicit constructor of REGEXP, in plain text format:/pattern/[flags]. The two statements in Example 4 are equivalent.
Example 4:
var Re1 = new RegExp ("\\d{5}"); var re2 =/\d{5}/;
3, string search and the use of the Exec () method
The Exec () method returns an array that holds the results of the match. If no match is found, the return value is null.
Example 5:
var reg=new RegExp ("(\\w+), (\\d+), (\\w+)", "GMI"), var m=reg.exec ("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)
Returns True if the string contains text that matches regexpobject, otherwise false.
Example 6:
var reg=new RegExp ("(\\w+), (\\d+), (\\w+)", "GMI"), var m=reg.test ("Lili,14,china"); alert (regexp.$1); alert (regexp.$2); alert (regexp.$3);
JS uses the Replace () method and regular expressions to search and replace instances of strings