【笔记】JS - RegExp对象

来源:互联网 发布:cj是什么意思网络用语 编辑:程序博客网 时间:2024/05/16 00:53

RegExp:正则表达式
用于存储检索模式

var patt1=new RegExp("e");

RegExp对象的方法:
1、test()
—检索字符串中的指定值,返回true或false

document.write(patt1.test("The best things in life are free"));

2、exec()
—检索字符串中的指定值,返回被找到的值,若没有,返回null

document.write(patt1.exec("The best things in life are free"));

输出为:e

例2:
可以向RegExp对象添加第二个参数,以设定检索。
例如,如果需要找到所有某个字符的所有存在,则可以使用 “g” 参数 (“global”)。
在使用 “g” 参数时,exec() 的工作原理如下:

  • 找到第一个 “e”,并存储其位置
  • 如果再次运行 exec(),则从存储的位置开始检索,并找到下一个 “e”,并存储其位置
do{result=patt1.exec("The best things in life are free");document.write(resule);}while(result!=null)

输出为:eeeeeenull
3、compile()
—用于改变RegExp
—既可以改变检索模式,也可以添加或删除第二个参数

var patt1=new RegExp("e");document.write(patt1.test("The best things in life are free"));patt1.compile("d");document.write(patt1.test("The best things in life are free"));

输出为:truefalse

0 0