JS USES the replace of method and regular expression to search and replace instances of strings


1. The use of JS string replacement and replace() method

The replace(regexp) method has two parameters. The first parameter can be a plain text string or a regexp object. The second argument can be a string or a function.

The following is an example of JS string substitution:

Case 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 $1, $2 years old, come from $3");
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) { //You can also use non-explicit arguments, 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, with each regular expression pattern corresponding to a RegExp instance. There are two ways to create an instance of a RegExp object.

Use the explicit constructor of RegExp, 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:

var re1 = new RegExp("\d{5}");
var re2 = /d{5}/;

  3. Search for strings and use of exec() methods

  The exec() method returns an array of matches. 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 test() method

RegExpObject. Test (string)

Returns true if the string string contains text that matches RegExpObject, or false otherwise.

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);