最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

引言

本瓜相信你一定經(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ù)做匹配的時候,會出錯,是因?yàn)橐粋€我們將要認(rèn)識的 —— 正則類型 lastIndex 屬性!

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

每次當(dāng)我們用正則 RegExp.exec() 和 RegExp.test() 進(jìn)行匹配的時候,如果返回為 true,lastIndex 屬性的值會發(fā)生變化,會變成正確匹配的子字符串的最后位置,并將此位置作為下次檢索的起始點(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") 則會從 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)文章

最新評論

青铜峡市| 寿光市| 木兰县| 丰台区| 铁岭县| 双流县| 宜兰市| 茂名市| 林周县| 章丘市| 衡东县| 个旧市| 车致| 无极县| 嘉荫县| 清河县| 宝兴县| 南岸区| 石台县| 特克斯县| 台东市| 阿克| 闽清县| 怀化市| 泉州市| 江津市| 湖北省| 鄂托克旗| 扶沟县| 高尔夫| 柏乡县| 宜兰县| 霞浦县| 丁青县| 曲沃县| 阿城市| 辉县市| 大渡口区| 腾冲县| 奈曼旗| 丰都县|