javascript正则表达式使用reg.test()时慎用全局查找/.../g属性
先看一道JavaScript題目,據說是國內某知名互聯網企業的JavaScript筆試題,如果對正則的全局匹配模式不了解的話可能會對下面的輸出結果感到疑惑。
[php]
var str = "123#abc";
var re = /abc/ig;
console.log(re.test(str)); //輸出ture
console.log(re.test(str)); //輸出false
console.log(re.test(str)); //輸出ture
console.log(re.test(str)); //輸出false
[/php]
在創建正則表達式對象時如果使用了“g”標識符或者設置它了的?global屬性值為ture時,那么新創建的正則表達式對象將使用模式對要將要匹配的字 符串進行全局匹配。在全局匹配模式下可以對指定要查找的字符串執行多次匹配。每次匹配使用當前正則對象的lastIndex屬性的值作為在目標字符串中開 始查找的起始位置。lastIndex屬性的初始值為0,找到匹配的項后lastIndex的值被重置為匹配內容的下一個字符在字符串中的位置索引,用來 標識下次執行匹配時開始查找的位置。如果找不到匹配的項lastIndex的值會被設置為0。當沒有設置正則對象的全局匹配標志時lastIndex屬性的值始終為0,每次執行匹配僅查找字符串中第一個匹配的項。可以通下面的代碼來查看在執行匹配相應的lastIndex 屬性的值。
[php]
var str = "123#abc";
var re = /abc/ig;
console.log(re.test(str)); //輸出ture
console.log(re.lastIndex); //輸出7
console.log(re.test(str)); //輸出false
console.log(re.lastIndex); //輸出0
console.log(re.test(str)); //輸出ture
console.log(re.lastIndex); //輸出7
console.log(re.test(str)); //輸出false
console.log(re.lastIndex); //輸出0
[/php]
這個時候可以在其中添加一條語句, 人工將位置歸零, 防止這個 "錯誤" 的發生:
[php]
var re = /^\w$/g;
re.test('a'); //返回true
re.lastIndex = 0; //歸零搜索的位置
re.test('b'); //返回true
[/php]
或者我們可以更簡單地直接將g去掉:
[php]
var re = /^\w$/;
re.test('a'); //返回true
re.test('b'); //返回true
[/php]
轉自:https://blog.csdn.net/leolu007/article/details/8576490
總結
以上是生活随笔為你收集整理的javascript正则表达式使用reg.test()时慎用全局查找/.../g属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: freeCodeCamp:Where a
- 下一篇: 「工具推荐」小众又实用的五款效率工具