RegExp 对象的三个方法:compile()、exec()、test()

时间:2023-03-09 04:33:40
RegExp 对象的三个方法:compile()、exec()、test()

这三个都是RegExp对象下的三个方法,使用方法是一致得。

使用方法:RegExpObject.方法()

方法解析:其实就是根据定义好的正则对象,调用对应的方法。

     1.RegExpObject.compile(RegExp,modifier)

     modifier 规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。

     compile用于改变和重新编译正则表达式。   

var str="Every man in the world! Every woman on earth!";

patt=/man/g;
str2=str.replace(patt,"person");
document.write(str2+"<br />"); patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
document.write(str2); 

输出:

Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!

对patt正则进行重新编译赋给patt

先是用person替换了man,然后重新定义patt正则,加了wo ,之后再次替换,这样man和woman都被替换掉了,其实可以直接写/(wo)?man/g这个正则,就能全部替换了。

    2.RegExpObject.exec(string)

    这个方法用于检索字符串中的正则表达式的匹配。匹配成功有值的话返回一个数组,里头存放匹配的结果,如果没找到匹配项则返回null.

var str = "Visit W3School";
var patt = new RegExp("W3School","g");
console.log(patt.exec(str))

  输出:["W3School"]

在str字符串中查找patt正则定义字符串,找到返回字符串数组

    3.RegExpObject.test(string)

    test方法跟exec的区别就是返回值不同,exec找到返回值数组,test找到返回true,没找到返回false

var str = "Visit W3School";
var patt1 = new RegExp("W3School");
console.log(patt1.test(str))

  输出:true