zoukankan      html  css  js  c++  java
  • 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的问题

  • 相关阅读:
    《构建之法》阅读报告
    教务管理系统类图及数据库E/R图
    设计模式:抽象工厂
    结对项目:四则运算程序测试
    Leetcode笔记之57和为s的连续正数序列
    Leetcode笔记之1103分糖果 II
    Leetcode笔记之199二叉树的右视图
    每日Scrum(9)
    每日Scrum(7)
    每日Scrum(6)
  • 原文地址:https://www.cnblogs.com/wjcnet/p/3810540.html
Copyright © 2011-2022 走看看