正则相关常用方法
1·test() 正则对象的方法
正则表达式跟字符串进行匹配,匹配成功返回true,否则返回false
2·search() 字符串对象方法
返回匹配到的字符的索引号,没有匹配到返回-1
3·match() 字符串对象方法
匹配到的字符串存入数组返回
4·replace 字符串对象方法
用新字符替换匹配到的字符
test示例
function test1() {
let str = 'abcdef'
let reg = /b/
let isSuccess = reg.test(str)
if(isSUccess) {
alert('匹配成功')
} else {
alert('匹配失败')
}
}
test1()
search示例
function test2() {
let str = 'abcedf'
let reg = /b/
let index = str.search(reg)
alert(index)
}
test2()
match示例
function test3(){
let str = "dgfhfg254bhku289gdhydy674";
let reg = /\b/
let arr = str.match(reg)
console.log(arr);
}
test3()
function test3(){
let str = "dgfhfg254bhku289gdhydy674";
let reg = /\b/g
let arr = str.match(reg)
console.log(arr);
}
test3()
replace示例
function test3() {
let = 'aaa'
let reg = /a/
let newArr = str.replace(reg,'b')
console.log(newArr);
}