1、replace():替换reg匹配字符串
var reg=/\d/; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.replace(reg,"--"));//AAA--BBBBCCCCDDDD //用--替换字符串中数字,但结果发现却只替换掉了第一个,因为reg默认匹配第个 //那么要替换所有的数字,需要在reg后面加个全部的参数 g var reg=/\d/g; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.replace(reg,"--"));//AAA--BBBB--CCCC--DDDD
2、split():按reg匹配的值拆分成数组
var reg=/\d/; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.split(reg));//["AAA", "BBBB", "CCCC", "DDDD"]
3、match():返回reg匹配的第个字符串
var reg=/\d/; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.match(reg));//"9" 返回第一个数字"9"
4、search():返回reg匹配的第一个字符串的位置,没有则返回-1
var reg=/\d/; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.search(reg)); //3 返回第个数字 9的位置
正则方法的调用是:reg.方法(字符串);
字符串方法的调用:字符串.方法(reg);
参数: g :全文查找
var reg=/\d/; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.replace(reg,"--"));//AAA--BBBBCCCCDDDD //用--替换字符串中数字,但结果发现却只替换掉了第一个,因为reg默认匹配第个 //那么要替换所有的数字,需要在reg后面加个全部的参数 g var reg=/\d/g; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.replace(reg,"--"));//AAA--BBBB--CCCC--DDDD
i :忽略大小写
var reg = /a/i; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.replace(reg,"--")); // --AAA9BBBB2CCCC3DDDD var reg = /a/; var str1 = "AAA9BBBB2CCCC3DDDD"; console.log(str1.replace(reg,"--")); //AA9BBBB2CCCC3DDDD
m:多行查找
这个有点不好理解,多行查找和全文查找有什么区别呢。我们来举个例子看看
//例:全文查找 替换所有的A var reg = /A/g; var str1 = "AAA9BBBB2CCCCAAAA3DDDD"; console.log(str1.replace(reg,"-")); // ---9BBBB2CCCC----3DDDD //例:多行查找 var reg = /A/m; var str1 = "AAA9BBBB2CCCCAAAA3DDDD"; console.log(str1.replace(reg,"-")); // -AA9BBBB2CCCCAAAA3DDDD //多行查找一般用于有换行的字符中 var reg = /^A/; var str1 = "BBBB9BBBB2CCCC\r\nAAAA3DDDD"; console.log(str1.replace(reg,"-")); //BBBB9BBBB2CCCC //AAAA3DDDD //字符串里有个换行符当正则匹配第一行后就结束了,所以这里就引用了换符符的功能 var reg = /^A/m; var str1 = "BBBB9BBBB2CCCC\r\nAAAA3DDDD"; console.log(str1.replace(reg,"-")); //BBBB9BBBB2CCCC //-AAA3DDDD //全文查找的范围大于多行查找