This article mainly introduces JS using the Replace () method and regular expressions to search and replace the string of instances, the need for friends can refer to the following
1, JS string replacement and replace () method of use replace (regexp,replacement) method has two parameters, the first parameter can be a plain text string or a RegExp object, specifically see RegExp object use The second argument is either a string or a function. Below is an example of JS string replacement: Example 1: code as follows: Var str= "Hello world!"; document.write (Str.replace (/world/, "Phper")); Example 2: The code is as follows: 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: code 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) {//can also use non explicit parameters, using arguments to obtain name = P1; age = p2; from = p3; retur N "She is" +p1+ "," +p2+ "years old, come from" +P3;} var rep=info.replace (Reg, Prase_info); Alert (rep); Aler (name); 2, the use of RegExp objects JavaScript provides a RegExp object to complete the operation and function of regular expressions, and each regular expression pattern corresponds to a regexp instance. There are two ways to create an instance of a RegExp object. using the explicit constructor of REGEXP, the syntax is: New REGEXP ("pattern" [, "Flags"]), using RegExp implicit constructor, in plain text format:/pattern/[flags]. The two statements in Example 4 are equivalent. Example 4: The code is as follows: var Re1 = new RegExp ("d{5}"); var re2 =/d{5}/; 3, String search, and the use of the Exec () method exec () method returns an array that holds the result of the match. If no match is found, the return value is null. Example 5: Code as follows: 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 string strings contain text that matches Regexpobject, otherwise returns false. Example 6: code 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);