Объекты регулярных выражений имеют свойство lastIndex
, которое используется по-разному в зависимости от флагов g
(global) и y
(sticky). Флаг y
(sticky) указывает регулярному выражению искать совпадения в lastIndex
и только в lastIndex
(не раньше или позже в строке).
Примеры стоят 1024 слова:
var str = "a0bc1";
// Indexes: 01234
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;
}
Примечание о совместимости :
У движка Firefox SpiderMonkey JavaScript годами был флаг y
, но он не входил в спецификацию до ES2015 (июнь 2015 г.). Кроме того, в течение довольно долгого времени у Firefox была ошибка в обработке флага y
относительно утверждения ^
, но это было исправлено где-то между Firefox 43 (имеет ошибку) и Firefox 47 (не делает). Очень старые версии Firefox (скажем, 3.6) имели y
и не имели ошибки, поэтому позже произошла регрессия (не определено поведение для флага y
), а затем исправлено.