JS笔记 RegExp 实例方法exec()和test()

exec()方法

该方法专门为捕获组设计,接受一个参数,即要应用模式的字符串,返回包含第一个匹配项信息的数组;没有匹配项时返回null。返回的数组包含两个额外属性index,input。index表示匹配项在字符串中的位置,input表示应用正则表达式的字符串。
在不设置全局标志时,在同一个字符串上多次调用exec()始终只返回第一个匹配项的信息。

例子

//不设置全局标志
let text = "cat, bat, sat, fat";
let pattern1 = /.at/;

let matches = pattern1.exec(text);
console.log(matches.index);     //0
console.log(matches[0]);        //cat
console.log(matches.lastIndex); //0

matches = pattern1.exec(text);
console.log(matches.index);     //0
console.log(matches[0]);        //cat
console.log(matches.lastIndex); //0

设置全局标志的情况下,每次调用exec()都会在字符串中继续查找新的匹配项

例子

let text = "cat, bat, sat, fat";
let pattern2 = /.at/g;

let matches = pattern2.exec(text);
console.log(matches.index);     //0
console.log(matches[0]);        //cat
console.log(matches.lastIndex); //3

matches = pattern2.exec(text);
console.log(matches.index);     //5
console.log(matches[0]);        //cat
console.log(matches.lastIndex); //8

pattern1不是全局模式,所以每次返回的都是第一个匹配项"cat",pattern2是全局模式,因此每次调用都会返回字符串中的下一个匹配项。

test()方法

该方法接受一个参数,在模式与参数匹配的情况下返回true,否则返回false。常用于if语句中。

例子

let text = "000-00-0000";
let pattern = /\d{3}-\d{2}-\d{4}/;
if(pattern.test(text)){
    console.log("The pattern is matched.");
}

RegExp实例继承的toLocaleString()和toString()都会返回正则表达式的字面量,与创建正则表达式的方式无关。valueOf()方法返回正则表达式本身。

你可能感兴趣的:(JS笔记 RegExp 实例方法exec()和test())