亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

引言

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

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"))

“不就是三個(gè) true 嗎?!”

在控制臺(tái)上打印試試?驚不驚喜、意不意外?

image.png

為什么是 true 、false 、true ?

原來這里,這里有個(gè)小坑需要注意下,用 test() 連續(xù)做匹配的時(shí)候,會(huì)出錯(cuò),是因?yàn)橐粋€(gè)我們將要認(rèn)識(shí)的 —— 正則類型 lastIndex 屬性!

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

每次當(dāng)我們用正則 RegExp.exec() 和 RegExp.test() 進(jìn)行匹配的時(shí)候,如果返回為 true,lastIndex 屬性的值會(huì)發(fā)生變化,會(huì)變成正確匹配的子字符串的最后位置,并將此位置作為下次檢索的起始點(diǎn)。如果返回為 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") 則會(huì)從 b 的位置往后搜索,搜不到 ab 了,返回 false ,同時(shí) lastIndex 重置為 0 ,然后第三次調(diào)用 pattern.test("abcd") 又能正確返回 true 了,lastIndex 也變成了 2。

不知道這個(gè)坑,你踩到過沒?

怎么解決呢?

方法一:手動(dòng)清理 lastIndex

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

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

方法二:用 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)解,不用手動(dòng)清理,存在則悉數(shù)返回成數(shù)組,不存在,返回 null

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

相關(guān)文章

最新評(píng)論