What is the purpose of the 'y' sticky pattern modifier in JavaScript RegExps?
The difference between y
and g
is described in Practical Modern JavaScript:
The sticky flag advances
lastIndex
likeg
but only if a match is found starting atlastIndex
, there is no forward search. The sticky flag was added to improve the performance of writing lexical analyzers using JavaScript...
As for a real use case,
It could be used to require a regular expression match starting at position
n
wheren
is whatlastIndex
is set to. In the case of a non-multiline regular expression, alastIndex
value of0
with the sticky flag would be in effect the same as starting the regular expression with^
which requires the match to start at the beginning of the text searched.
And here is an example from that blog, where the lastIndex
property is manipulated before the test
method invocation, thus forcing different match results:
var searchStrings, stickyRegexp;
stickyRegexp = /foo/y;
searchStrings = [
"foo",
" foo",
" foo",
];
searchStrings.forEach(function(text, index) {
stickyRegexp.lastIndex = 1;
console.log("found a match at", index, ":", stickyRegexp.test(text));
});
Result:
"found a match at" 0 ":" false
"found a match at" 1 ":" true
"found a match at" 2 ":" false