2010-12-27 11 views

Odpowiedz

30

Obiekty wyrażeń regularnych mają właściwość lastIndex, która jest używana na różne sposoby w zależności od flag g (globalna) i y (lepka). Flaga (lepki) y mówi wyrażenie regularne szukać meczu w lastIndex i tylko w lastIndex (nie wcześniej lub później w ciągu).

Przykładami są warte 1024 słów:

var str = "a0bc1"; 
 
// Indexes:
 

 
var rexWithout = /\d/; 
 
var rexWith = /\d/y; 
 

 
// Without: 
 
rexWithout.lastIndex = 2;   // (This is a no-op, because the regex 
 
            // doesn't have either g or y.) 
 
console.log(rexWithout.exec(str)); // ["0"], found at index 1, because without 
 
            // the g or y flag, the search is always from 
 
            // index 0 
 

 
// With, unsuccessful: 
 
rexWith.lastIndex = 2;    // Says to *only* match at index 2. 
 
console.log(rexWith.exec(str)); // => null, there's no match at index 2, 
 
            // only earlier (index 1) or later (index 4) 
 

 
// With, successful: 
 
rexWith.lastIndex = 1;    // Says to *only* match at index 1. 
 
console.log(rexWith.exec(str)); // => ["0"], there was a match at index 1. 
 

 
// With, successful again: 
 
rexWith.lastIndex = 4;    // Says to *only* match at index 4. 
 
console.log(rexWith.exec(str)); // => ["1"], there was a match at index 4.
.as-console-wrapper { 
 
    max-height: 100% !important; 
 
}


Zgodność Note:

silnik SpiderMonkey JavaScript Firefoksa miał flagę y lat, ale to nie było Część specyfikacji do ES2015 (Czerwiec 2015). Ponadto, przez pewien czas Firefox miał a bug in the handling of the y flag w odniesieniu do asercji ^, ale został ustalony gdzieś pomiędzy Firefox 43 (ma błąd) i Firefox 47 (nie). Bardzo stare wersje Firefoksa (powiedzmy 3.6) miały y i nie miały błędu, więc nastąpiła regresja, która nastąpiła później (nie zdefiniowano zachowania dla flagi y), a następnie naprawiono.