• js正则表达式常用方法总结


    1、test()  方法用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回 true,否则返回 false。

    var patt = /e/;
    patt.test("The best things in life are free!");   //字符串中含有 "e",所以该实例输出为:true        
    等效于 /e/.test("The best things in life are free!")

    var reg = /(d{4})-(d{2})-(d{2})/; var dateStr = '2018-04-18'; reg.test(dateStr); //true

    2、replace()   字符串替换

    使用正则表达式且不区分大小写将字符串中的 Microsoft 替换为 Runoob 
    var txt = str.replace(/microsoft/i,"Runoob"); replace() 方法使用正则表达式
    var txt = str.replace("Microsoft","Runoob"); replace() 方法使用字符串

     3、search() 方法 。用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串,并返回子串的起始位置。

    var str = "Visit Runoob!";
    var n = str.search(/Runoob/i);     //6

     4、match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。

    var str="Hello world!"
    document.write(str.match("world") + "<br />")       //world
    document.write(str.match("World") + "<br />")       //null
    document.write(str.match("worlld") + "<br />")      //null
    document.write(str.match("world!"))                 //world!


    var str="1 plus 2 equal 3"
    document.write(str.match(/d+/g))         //1,2,3
     
  • 相关阅读:
    实验二 20159213
    读书笔记二 20159213
    读书随笔 20159213
    keycode对照表
    jquery ajax中各个事件执行顺序如下
    移动端web开发技巧
    zepto处理touch事件
    CSS控制文字只显示一行,超出部分显示省略号
    input按钮的事件处理大全
    jquery中ajax处理跨域的三大方式
  • 原文地址:https://www.cnblogs.com/zouhong/p/11878921.html
Copyright © 2020-2023  润新知