欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js正則test匹配的踩坑及解決

 更新時間:2022年07月08日 09:48:21   作者:掘金安東尼  
這篇文章主要為大家介紹了正則test匹配的踩坑示例講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

引言

本瓜相信你一定經(jīng)常用以下這種最最簡單的正則來判斷字符串中是否存在某個子字符(別說了,我就是)??

const pattern = /ab/g
pattern.test("abcd") // true

這樣去匹配,有什么問題嗎?

不急,現(xiàn)在來讓你猜一下,以下代碼的輸出?

const pattern = /ab/g
console.log(pattern.test("abcd"))
console.log(pattern.test("abcd"))
console.log(pattern.test("abcd"))

“不就是三個 true 嗎?!”

在控制臺上打印試試?驚不驚喜、意不意外?

image.png

為什么是 true 、false 、true ?

原來這里,這里有個小坑需要注意下,用 test() 連續(xù)做匹配的時候,會出錯,是因為一個我們將要認(rèn)識的 —— 正則類型 lastIndex 屬性!

lastIndex 屬性用于規(guī)定下次匹配的起始位置。

每次當(dāng)我們用正則 RegExp.exec() 和 RegExp.test() 進行匹配的時候,如果返回為 true,lastIndex 屬性的值會發(fā)生變化,會變成正確匹配的子字符串的最后位置,并將此位置作為下次檢索的起始點。如果返回為 false,lastIndex 重置為 0 ;

所以,我們這樣打印試試就知道了:

const pattern = /ab/g
console.log(pattern.test("abcd")) // true
console.log(pattern.lastIndex) // 2
console.log(pattern.test("abcd")) // false
console.log(pattern.lastIndex) // 0
console.log(pattern.test("abcd")) // true
console.log(pattern.lastIndex) // 2

當(dāng)我們第一次調(diào)用 pattern.test("abcd") ,pattern.lastIndex 為 2, 即字母 b 的位置,當(dāng)再次調(diào)用 pattern.test("abcd") 則會從 b 的位置往后搜索,搜不到 ab 了,返回 false ,同時 lastIndex 重置為 0 ,然后第三次調(diào)用 pattern.test("abcd") 又能正確返回 true 了,lastIndex 也變成了 2。

不知道這個坑,你踩到過沒?

怎么解決呢?

方法一:手動清理 lastIndex

const pattern = /ab/g
console.log(pattern.test("abcd")) // true
pattern.lastIndex = 0
console.log(pattern.test("abcd")) // true

不過,這樣手動清理很麻煩,顯得很笨,所以建議用方法二。

方法二:用 match 來匹配

const pattern = /ab/g
console.log("abcd".match(pattern)) // ['ab']
console.log("abcdab".match(pattern)) // ['ab', 'ab']
console.log("123".match(pattern)) // null

match 是匹配的更優(yōu)解,不用手動清理,存在則悉數(shù)返回成數(shù)組,不存在,返回 null

以上就是正則test匹配的踩坑及解決的詳細(xì)內(nèi)容,更多關(guān)于正則test匹配坑的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論