JavaScript學習筆記整理Day11

來源:互聯網
上載者:User

標籤:整理   string   lob   world   截取字串   執行   exec   test   str   

一.詞邊界、正向預查、反向預查

  1.詞邊界

    \b詞邊界(單詞的邊界)

    \B非詞邊界

     //匹配出第二個hello        var str = ‘hellobaby hello‘;        var reg = /\bhello\b/;        console.log(str.match(reg));        //匹配出第一個 hello        var reg = /\bhello\B/;        console.log(str.match(reg));

  2.正向預查(?=後面是。。。。)

        var str = ‘hellobaby helloworld‘;        //要求匹配出第二個hello        var reg = /hello(?=world)/;        console.log(str.match(reg));        

  3.反向預查(?!後面不是。。。)

     var reg = /hello(?!world)/;        console.log(str.match(reg));

二.字串邊界---用於精確匹配

  1.^以指定字元開頭

  2.$以指定字元結尾

var reg = /^[a-zA-Z]\w{5,11}$/;

三.Regex修飾符

  1.g 執行全匹配

  2.i執行對大小寫不敏感

  3.m執行多行匹配

 var str = ‘Helloworld helloworld‘; var reg = /hello/gi;   console.log(str.match(reg)); var str = ‘Lorem nihao \rLorem hello‘;

四.用於模式比對的String方法

  1.match()  正則匹配 返回匹配的內容  數組

  2.search()  尋找      返回首次出現的索引     如果不存在返回-1

var str = ‘hello niheao‘;
var reg = /e/g; console.log(str.search(reg));

  3.split() 使用正則截取字串 返回數組

var str = ‘border-left-color‘;var reg = /-/;var arr = str.split(reg);        console.log(arr);

  4.replace() 正則替換

var str = ‘hello world, hello baby, hello shabi‘;        //將字串中的hello替換成 hi                    //1. 老字串 或者 正則                    //2.  新內容var newStr = str.replace(‘hello‘,‘hi‘); //只替換一個        console.log(newStr);var newStr = str.replace(/hello/g,‘hi‘); //使用正則替換        console.log(newStr);

五.正則對象的方法

  1.test()  檢測是否匹配

var str = ‘abcdef abc hello‘;var reg = /Q/;        console.log(reg.test(str));var reg = /o/;        console.log(reg.test(str));

  2.exec()  正則匹配 返回匹配的內容 不支援g

var str = ‘hello world, hello baby, hello shabi‘;

 var reg = /hello/;

 console.log(reg.exec(str));

JavaScript學習筆記整理Day11

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.