1. Replacement of JS strings and the use of replace() method
The replacement(regexp, replacement) method has two parameters. The first parameter can be a plain text string or a RegExp object. For details, please 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:
The code copy is as follows:
var str="Hello world!";
document.write(str.replace(/world/, "phper"));
Example 2:
The code copy 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:
The code copy is as follows:
var reg=new RegExp("(//w+),(//d+),(//w+)","gmi");
var info="Lili,14,China";
var name, age, from;
function vote_info(m,p1,p2,p3) {// You can also use non-explicit parameters and use arguments to obtain them.
name = p1;
age = p2;
from = p3;
return "She is "+p1+", "+p2+" years old, come from "+p3;
}
var rep=info.replace(reg, purchase_info);
alert(rep);
alert(name);
2. Use of RegExp objects
JavaScript provides a RegExp object to complete operations and functions related to regular expressions. Each regular expression pattern corresponds to a RegExp instance. There are two ways to create instances of RegExp objects.
Use RegExp's explicit constructor, the syntax is: new RegExp("pattern"[,"flags"]); use RegExp's implicit constructor, using the plain text format: /pattern/[flags]. The two statements in Example 4 are equivalent.
Example 4:
The code copy is as follows:
var re1 = new RegExp("//d{5}");
var re2 = //d{5}/;
3. Search strings and the use of exec() method
The exec() method returns an array where the matching results are stored. If no match is found, the return value is null.
Example 5:
The code copy is 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 test() method
RegExpObject.test(string)
Return true if the string string contains text that matches RegExpObject, otherwise false.
Example 6:
The code copy 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);