RegExp 对象

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

当您检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp 就是这种模式。这种模式既可以是一个单独的字符,也可以包含更多的字符,可以用于解析,检查格式,替换等。

RegExp 是正则表达式的缩写。

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

定义了名为 patt1 的 RegExp 对象,其模式是 "e":

var patt1 = new RegExp("e")

RegExp 对象有 3 个方法:

  • test()
  • exec()
  • compile()

test()

test() 方法检索字符串中的指定值。返回值是 true 或 false。

exec()

exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。

可以向ExgExp对象添加第二个参数g,用来指定检索

使用“g”参数,exec的原理:

  • 找到第一个“e”,并存储其位置
  • 如果再次运行exec(),则从存储的位置开始检索,并找到下一个“e”,并存储其位置

代码:

var patt3 = new RegExp("e","g");
var result;
do{
    result = patt3.exec("hello,world,free")
    document.write(result)
}
while (result != null)

结果:

compile()

compile() 方法用于改变 RegExp

compile() 既可以改变检索模式,也可以添加或删除第二个参数。

代码:

var patt4 = new RegExp("e");
document.write("<p> patt4.test('hello') = "+ patt4.test("hello") +"</p>")
patt4.compile("d")
document.write("<p> patt4.test('hello') = "+ patt4.test("hello") +"</p>")

结果:

results matching ""

    No results matching ""