淺談 js 正則之 test 方法

來源:互聯網
上載者:User

標籤:c   style   class   blog   java   a   

其實我很少用這個,所以之前一直沒注意這個問題,自從落葉那廝寫了個變態的測試我才去看了下這東西。
先來看個東西吧。

var re = /\d/;console.log( re.test("1") );console.log( re.test("1") );console.log( re.test("1") );console.log( re.test("1") );

全部是 true 沒問題。。

但是你把 /\d/; 改成 /\d/g; 再試試。

再次修改:

console.log( /\d/g.test("1") );console.log( /\d/g.test("1") );console.log( /\d/g.test("1") );console.log( /\d/g.test("1") );

全部是 true,這究竟是為什麼呢?

這些結果相當有意思,當然高手自然知道為什麼,如果你知道的話,下面其實可以跳過不用看了,全是水文而已。。

正則裡有一個 lastIndex 的屬性,是下一次匹配的開始位置。

var re = /\d/g;console.log( re.test("1"), re.lastIndex );console.log( re.test("1"), re.lastIndex );console.log( re.test("1"), re.lastIndex );console.log( re.test("1"), re.lastIndex );

可以看到 第一次匹配結果為 true 表示匹配成功,此時 lastIndex 記錄下一次匹配的起始位置為 1。
於是第二次匹配的時候 從 "1" 字串索引 1 的位置匹配,當然就匹配失敗了,因為這個字串只有一個字元,他的索引是 0。

而 /\d/g.test("1") 這個為什麼每次匹配成功能呢?
因為它直接用正則字面量,相當於每次重新建立一個正則對象,lastIndex 屬性是初始值 0。
所以每次都能匹配成功。

現在是不是理解了,包括 exec 也一樣,每次匹配一個,lastIndex 記錄下次匹配的起始位置。
如果非要用一個正則對象的,那就只有每次 test 前重設 lastIndex 了,這樣才能保證他不出以外。

var re = /\d/g;console.log( re.test("1") );re.lastIndex = 0;console.log( re.test("1") );re.lastIndex = 0;console.log( re.test("1") );re.lastIndex = 0;console.log( re.test("1") );

好了,今天修改文法高亮外掛程式花了不少時間,所以水了一篇,望大家海涵。。

 

聯繫我們

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