Ответ 1
Объекты регулярных выражений имеют свойство lastIndex
, которое используется по-разному в зависимости от флагов g
(global) и y
(sticky). Флаг y
(липкий) указывает регулярному выражению искать совпадение в 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 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;
}