2013-03-25 72 views

回答

9

g是重複的搜索。它將正則表達式對象更改爲迭代器。如果你想使用test函數來檢查您的字符串根據你的模式是有效的,刪除此修改器:

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead"; 

test功能,違背replacematch不消耗整個迭代,這讓它處於「不良」狀態。在使用test函數時,您應該永遠不要使用此修飾符。

+0

將它保存最近發現指數的道在不同的'測試()'調用 – 2013-03-25 08:16:40

+0

@ArunPJohny我不認爲它可以永遠做有意義的使用「G」標誌和測試功能。 – 2013-03-25 08:21:34

+0

是的,這是正確的 – 2013-03-25 08:22:17

3

因爲您設置了g修飾符。

刪除它爲你的情況。

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead"; 
7

您不希望將gi與pattern.test結合使用。 g標誌意味着它會跟蹤你正在運行的地方,所以它可以被重用。因此,相反,你應該使用:

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead"; 

console.log('1', pattern.test(name)); 
console.log('1', pattern.test(name)); 

此外,您還可以使用/.../[flags]語法正則表達式,像這樣:

var pattern = /mstea/i; 
3

這是不是一個錯誤。

g導致它在第一次匹配後執行下一個嘗試匹配子字符串。這就是爲什麼它在每次嘗試中都返回false。

First attempt: 
It is testing "Amanda Olmstead" 

Second attempt: 
It is testing "d" //match found in previous attempt (performs substring there) 

Third attempt: 
It is testing "Amanda Olmstead" again //no match found in previous attempt 

... so on 

MDN頁Regexp.exec狀態:

如果你的正則表達式使用「G」標誌,你可以使用exec 方法多次找到相同的字符串匹配連續。 當你這樣做時,搜索在海峽的由 正則表達式的lastIndex屬性

MDN頁test國家指定的開始:

與EXEC(或結合它),多次測試 在同一個全球正則表達式實例將提前超過 以前的比賽。