RegExp() 对象

来源:互联网 发布:淘宝全职客服工资多少 编辑:程序博客网 时间:2024/06/15 06:49

1.compile()

compile() 方法用于在脚本执行过程中编译正则表达式。
也可用于改变和重新编译正则表达式。

function myFunction(){        var str="Every man in the world! Every woman on earth!";        var patt=/man/g;//全局匹配man,        var str2=str.replace(patt,"person");//把man用person替换        console.log(str2);        console.log(str);        patt=/(wo)?man/g;        patt.compile(patt);//通过 compile() 方法,改变正则表达式,用 "person" 替换 "man""woman",        str2=str.replace(patt,"person");//        console.log(str2);//返回Every person in the world! Every person on earth!    }    myFunction();

2.compile()

exec() 方法用于检索字符串中的正则表达式的匹配。
如果字符串中有匹配的值返回该匹配值,否则返回 null。

function myFunction(){        var str="Hello world!";        var patt=/Hello/g;        var result=patt.exec(str);        console.log("Returned value: " + result);//返回Hello        patt=/W3Schools/g;        result=patt.exec(str);        console.log("<br>Returned value: " + result);//返回null    }    myFunction();

3.compile()

test() 方法用于检测一个字符串是否匹配某个模式.
如果字符串中有匹配的值返回 true ,否则返回 false。

function myFunction(){        var str="Hello world!";        var patt=/Hello/g;        var result=patt.test(str);        console.log("Returned value: " + result);//返回true        patt=/W3CSchool/g;        result=patt.test(str);        console.log("<br>Returned value: " + result);//返回false    }    myFunction();