正则常用方法test,match,search,replace

时间:2022-09-01 18:37:13

test:
reg.test(str) 找到返回true,否则false 找到第一个后就会停止向后找

let str = 'bacdera';
let reg = /a/;
console.log(reg.test(str))   =>true

match:
str.match(reg) 不匹配返回null ,匹配到就返回对应的数组

let str = 'abaacdera';
let reg = /a/;
let arr2 = str.match(reg);
console.log(arr2)      =>["a", index: 0, input: "abaacdera", groups: undefined]   看着像一个数组,其实不是。
typeof(arr2)   =>    object

let reg = /a/g;
let arr3 = str.match(reg);
console.log(arr3)    => ["a", "a", "a", "a"]  是一个数组

let reg = /a+/g;
 let arr4 = str.match(reg);
console.log(arr4)    => ["a", "aa", "a"]  是一个数组

search:
str.search(reg) 匹配成功返回对应得位置,不成功返回 -1

let str = 'abaacdera';
let reg = /aa/;
let n= str.search(reg);
console.log(n)    =>2

replace:
str.replace(reg,newstring) newstring需要替换成的东西 返回替换完成后的字符串

let str = 'abaacdera';
let reg = /a/;
let str2 = str.replace(reg,'你好');
console.log(str2)    =>'你好baacdera'

let str = 'abaacdera';
let reg = /a/g;
let str2 = str.replace(reg,'你好');
console.log(str2)     =>'你好b你好你好cder你好'

let str = 'abaacdera';
let reg = /az/g;
let str2 = str.replace(reg,'你好');
console.log(str2)     =>'abaacdera'