系统整理一下JS正则相关api
一直不太熟悉js正则相关的函数(更熟悉正则的匹配方式),每次用到相关函数都要查文档,今天抽时间整理一下相关api
正则自身的api
下面这两个函数都是正则原型链上的函数
test
test就是检测一个字符串是否可以被匹配,如果可以返回true,不可以返回false
用法
RegExp.test(str) //true of false
举个例子
/^abc$/.test('abc') //true
/^abc$/.test('abcd') //false
只要能匹配就会返回true,比如下面这种情况
/a/.test('abc') //true
exec
区别于test,exec会返回匹配结果构成的数组,不能匹配就返回null
用法
RegExp.exec(str) //null or Array
举个例子
/a/.exec('aaaaabc') //["a"]
多测试几个例子可以发现js的正则存在 状态,每次匹配都会更新返回值的index属性(本次匹配时做最左边元素的位置)
例子
let regexp = /abcc?/g
let str = 'abcabcabccc'
console.log(regexp.exec(str)) // ['abc',index:0,input:'abcabcabccc',groups:undefined]
console.log(regexp.exec(str)) // ['abc',index:3,input:'abcabcabccc',groups:undefined]
console.log(regexp.exec(str)) // ['abcc',index:6,input:'abcabcabccc',groups:undefined]
数组内的每一项就是本次与正则匹配的返回值(正则内的()会产生新的匹配项,这个一会再看),可以看到每次调用返回值的index都在更新,数组内容也在更新。
最后看一下正则内的 ()对exec结果的影响
let regexp = /abc(c)?/g
let str = 'abcabcabccc'
console.log(regexp.exec(str)) //['abc',undefined,index:0,input:'abcabcabccc',groups: undefined]
console.log(regexp.exec(str)) //['abc',undefined,index:3,input:'abcabcabccc',groups: undefined]
console.log(regexp.exec(str)) //['abcc','c',index:6,input:'abcabcabccc',groups:undefined]
括号内的匹配项也会出现在数组内,如果没有匹配到就是undefined
数组相关的api
毕竟正则是用来处理字符串的,数组也有一些相关的api
match
用正则取匹配字符串,返回可以匹配的字符串数组
用法
str.match(RegExp) // Array
match相对来说没有exec那么复杂,就是返回匹配项构成的数组
举个例子
let regexp = /ab(c)/g
let str = 'abcabcabccc'
console.log(str.match(regexp)) // ['abc','abc','abc']
就是返回一个普通的数组,括号内的项也不会影响返回值
replace和split
这两个用法就比较简单了,看一下就懂
let regexp = /ab(c)/g
let str = 'abcabcabccc'
console.log(str.replace(regexp, '-')) // ---cc
let regexp = /ab(c)/g
let str = 'abcabcabccc'
console.log(str.split(regexp)) //['','c','','c','','c','cc']
这里发现()会对split结果产生影响, ()内的值也会进行一次额外分割