正则表达式String对象的4个方法

 1 // String对象的4个使用正则表达式的方法
 2 
 3 1、match(pattern)
 4     返回pattern中的子串或null
 5 2、replace(pattern,replacement)
 6     用replacement替换pattern
 7 3、search(pattern)
 8     返回字符串中pattern开始位置
 9 4、split(pattern)
10     返回字符串指定pattern拆分的数组
11 
12 
13 
14 //使用match方法获取匹配数组
15 
16 var pattern=/Box/i;        //没有开启全局
17 var str='This is a Box!That is a Box too!';
18 alert(str.match(pattern));    //匹配到第一个字符串返回数组
19 
20 
21 var pattern=/Box/i;    
22 var str='This is a Box!That is a Box too!';
23 var a=str.match(pattern);
24 alert(a[0]);    //证明了是数组
25 
26 
27 var pattern=/Box/gi;    //开启了全局
28 var str='This is a Box!That is a Box too!';
29 alert(str.match(pattern));    //将所有pipe的字符串组合成数组返回
30 
31 
32 
33 // 使用search来查找匹配数据
34 
35 var pattern=/Box/i;
36 var str='This is a Box!That is a Box too!';
37 alert(str.search(pattern));        //返回的第一个匹配的位置    PS:因为search查到即返回,所以无需g(全局)。
38 
39 
40 var pattern=/xox/i;
41 var str='This is a Box!That is a Box too!';
42 alert(str.search(pattern));        //找不到匹配,返回-1
43 
44 
45 
46 // 使用replace替换匹配到的数据
47 
48 var pattern=/Box/i;        //没有开启全局
49 var str='This is a Box!That is a Box too!';
50 alert(str.replace(pattern,'Tom'));        //返回替换后的字符串,只限第一个
51 
52 
53 var pattern=/Box/gi;        //开启全局
54 var str='This is a Box!That is a Box too!';
55 alert(str.replace(pattern,'Tom'));        //返回替换后的字符串,所有匹配都会被替换
56 
57 
58 
59 // 使用split拆分成字符串数组
60 var pattern=/!/gi;
61 var str='This is a Box!That  is a Box too!';
62 alert(str.split(pattern));
63 alert(str.split(pattern).length);
View Code
高否?富否?帅否? 否? 滚去学习!
原文地址:https://www.cnblogs.com/baixc/p/3379736.html