huakaiyueluo

导航

Js正则表达式学习之test和compile的简单介绍

RegExp 对象用于规定在文本中检索的内容。

定义 RegExp

RegExp 对象用于存储检索模式。

通过 new 关键词来定义 RegExp 对象。以下代码定义了名为 patt1 的 RegExp 对象,其模式是 "e":

test方法如下

var patt1=new RegExp("e");
RegExp 对象有 3 个方法:test()、exec() 以及 compile()。
patt1.test("the best things in life are free")
结果:true
patt1.test("x");
结果:false
var patt2=/e/
patt2.test("ee")
true
var patt2="/e/";
patt2
"/e/"
patt2.test("xxx");
TypeError: undefined is not a function
从上述中看出,"/e/"和/e/区别太大了,前者只是一个字符串,而后者是一个正则表达式对象,即RegExp对象

  

compile方法如下

compile() 方法用于改变 RegExp。
compile() 既可以改变检索模式,也可以添加或删除第二个参数。
var patt1=new RegExp("e");

console.log(patt1.test("The best things in life are free"));

patt1.compile("d");

console.log(patt1.test("The best things in life are free"));
由于字符串中存在 "e",而没有 "d",以上代码的输出是:
true false

 

总结:上面的简单介绍,只是解决怎样用test和compile的问题

 

posted on 2014-06-26 17:40  huakaiyueluo  阅读(2302)  评论(0编辑  收藏  举报