方法 | 含义 |
match(pattern) | 返回pattern中的子串或者null |
replace(pattern, replacement) | 用replacement代替pattern |
search(pattern) | 返回字符串中第一次出现pattern的位置 |
split(pattern) | 返回字符串按指定的pattern拆分的数组 |
1.使用match()方法获取匹配数组
var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.match(pattern)); //返回box,box
2.使用search()来查找匹配数据
var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.search(pattern)); //返回10,从0开始数;同时search()本来就是全局查找,所以无需加“g”。
3.使用replace()来替换匹配到的数据
var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.replace(pattern,'AK-47')); //返回This is a AK-47! That is a AK-47!
4.使用split()来拆分字符串成数组
var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.split('!')); //返回This is a Box, That is a Box, 两个感叹号故拆分成长度为3的数组