The sticky flag /y basically uses the lastIndex? property to mark the beginning of its matching flow. Like the global flag /g, sticky can match a pattern many times in a given string.
For a given regexp pattern, the sticky option starts its search with lastIndex value as 0. On successful match at this position, it updates the lastIndex value to the index after the match. This flag wants to see a continuous sequence of given pattern on a given input string. If it encounters a break or gap in the sequence, it would be stop matching, even if the pattern is present further down the input string.
Lets see this in action. The given regexp pattern is ([a-z]m):
which typically matches a string like am:, pm:, etc. It starts its search with lastIndex value as 0. It first encounters the string am:
and updates the lastIndex to 3.
Now it continues the search with new lastIndex value of 3 and successfully finds pm:
and the lastIndex gets updated to 6. This process is continued as long as it finds the pattern at the new lastIndex positions. This way, this flag wants to see a continuous sequence of given pattern on a given input string.
This flow gets interrupted with the part ptm
and it stops the search. The sticky flag, unlike the /g flag, doesn't care even if the same pattern of text is present further down the line.
Note The initial value of lastIndex need not be 0 always. It can be set to a desired value and the search process kicks off from that position.
In this case, there is a break in the sequence with the strings ptm
.
am:pm:am:ptm:atm:sm:pm::am:rm:am:nm:pm
match | position | $1 |
---|---|---|
am: | 0 | am |
pm: | 3 | pm |
am: | 6 | am |
For the same pattern, the global flag matches all occurances. If you set both sticky and global, sticky flag is applied and the global flag is ignored. Try setting sticky flag and see the behavior in the below panel.
am:pm:am:ptm:atm:sm:pm::am:rm:am:nm:pm
match | position | $1 |
---|---|---|
am: | 0 | am |
pm: | 3 | pm |
am: | 6 | am |
tm: | 10 | tm |
tm: | 14 | tm |
sm: | 17 | sm |
pm: | 20 | pm |
am: | 24 | am |
rm: | 27 | rm |
am: | 30 | am |
nm: | 33 | nm |
The lastIndex can be set to a desired position. In the below panel, it is set to the position 14. In this case, the searching starts at 14 and ends with the gap introduced with ::
.
am:pm:am:ptm:atm:sm:pm::am:rm:am:nm:pm
match | position | $1 |
---|---|---|
tm: | 14 | tm |
sm: | 17 | sm |
pm: | 20 | pm |