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的问题

  • 相关阅读:
    寒假学习报告05
    寒假学习报告04
    微信推送信息,支付宝支付接口
    Vue组件生成依赖文件,contentype
    redis之列表字典操作
    drf版本控制redis基础
    drf分页器,url控制器,解析器,响应器
    drf认证权限频率
    drf视图认证组件
    drf序列化组件
  • 原文地址:https://www.cnblogs.com/wjcnet/p/3810540.html
Copyright © 2011-2022 走看看