正則的lastIndex 屬性

2022-01-22 04:37:42 字數 1619 閱讀 8653

簡介:正則的lastindex 屬性用於規定下次匹配的起始位置。注意:該屬性只有設定標誌 g 才能使用。

上次匹配的結果是由方法 regexp.exec() 和 regexp.test() 找到的,它們都以 lastindex 屬性所指的位置作為下次檢索的起始點。這樣,就可以通過反覆呼叫這兩個方法來遍歷乙個字串中的所有匹配文字。

注意:該屬性是可讀可寫的。只要目標字串的下一次搜尋開始,就可以對它進行設定。當方法 exec() 或 test() 再也找不到可以匹配的文字時,它們會自動把 lastindex 屬性重置為 0。

例子一:在字串中全域性試試子字串 "ain" , 並輸出匹配完成之後的 lastindex 屬性:

例子二:多次檢索,列印出lastindex的位置,當檢索到最後沒有檢索出符合的就從頭開始檢索

var str="

the rain in spain stays";

var patt=/ain/g;

console.log(patt.test(str))

//true

console.log(patt.lastindex)//

8console.log(patt.test(str))//

true

console.log(patt.lastindex)//

17console.log(patt.test(str))//

false

console.log(patt.lastindex)//

0console.log(patt.test(str))//

true

console.log(patt.lastindex)//

8

例子三:如何避免因由於lastindex引起bug:每次都建立乙個新的regexp就 可以避免這個問題

var str="

the rain in spain stays";

console.log(/ain/g.test(str))//

true

console.log(/ain/g.lastindex)//

0console.log(/ain/g.test(str))//

true

console.log(/ain/g.lastindex)//

0console.log(/ain/g.test(str))//

false

console.log(/ain/g.lastindex)//

0console.log(/ain/g.test(str))//

true

console.log(/ain/g.lastindex)//

0

正則的lastIndex 屬性

簡介 正則的lastindex 屬性用於規定下次匹配的起始位置。注意 該屬性只有設定標誌 g 才能使用。上次匹配的結果是由方法 regexp.exec 和 regexp.test 找到的,它們都以 lastindex 屬性所指的位置作為下次檢索的起始點。這樣,就可以通過反覆呼叫這兩個方法來遍歷乙個字...

正規表示式物件的lastIndex屬性

js中正規表示式的使用方式有兩種,一種是正規表示式物件的方法,一種是字串物件的方法,前者有exec str test str 兩個方法,後者有match regexp replace regexp search regexp split search 四個方法。當作為正規表示式物件的方法使用時,要特...

lastIndex對正則結果的影響

今天遇到乙個問題,用正規表示式去檢查同乙個字串時,交替返回true和false。無奈之下,重新翻了翻權威指南,發現罪魁禍首原來是lastindex。可在控制台嘗試下 let reg d g undefined reg.test 1 true reg.test 1 false lastindex在權威...