javascript進階文法三

來源:互聯網
上載者:User

標籤:3.1   運算子   rom   1.3   字串替換   asc   roman   res   alert   

一、js的Regex

  1、什麼是Regex

    Regex(regular expression)是一個描述字元模式的對象,ECMAScript的RegExp類表示Regex,而String和RegExp都定義了使用Regex進行強大的模式比對和文本檢索與替換的函數。

  2、Regex的建立方式:

    2.1 方式1:new方式建立

      var box = new RegExp(‘box‘, ‘ig‘);

    2.2 方式2:字面量方式建立

      var box = /box/ig;

    2.3第一個參數表示被匹配的字串,第二個參數表示正則的匹配方式,主要有三個匹配類型分別為:

      i:忽略被匹配字串的大小。

      g:被匹配的字串進行全域匹配。

      m:被匹配的字串進行多行匹配。

  3、Regex的匹配方法:

    3.1方法1:new()方法   

      3.1.1使用new運算子的test方法樣本:

        var pattern = new RegExp(‘box‘, ‘i‘); //建立正則模式,不區分大小寫

        var str = ‘This is a Box!‘; //建立要比對的字串

        alert(pattern.test(str)); //通過test()方法驗證是否匹配,返回的是個布爾值,true或flase

      3.1.2使用字面量方式的test方法樣本:

        var pattern = /box/i; //建立正則模式,不區分大小寫

        var str = ‘This is a Box!‘;

        alert(pattern.test(str));

      3.1.3使用一條語句實現正則匹配

        alert(/box/i.test(‘This is a Box!‘)); //模式和字串替換掉了兩個變數

    3.2方法2:exec()方法

      3.2.1方法與test()類似。

 

        var pattern = /box/i;  //建立正則模式,不區分大小寫

 

        var str = ‘This is a Box!‘;  //建立要比對的字串

 

        alert(pattern.exec(str)); //匹配了返回數組,否則返回null

 

      

 

      

javascript進階文法三

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.