/y (Sticky)
What is /y (Sticky)?
/y (Sticky): Matches only at the lastIndex position of the regex; does not scan forward. The y flag in JavaScript makes a regex sticky. It only tries to match at the exact position stored in lastIndex, and fails if the text there does not fit. It never searches further along the string.
Frequently asked questions about /y (Sticky)
How is /y (Sticky) used in practice?
This is what you need for a tokenizer or a simple parser. You read one token, move lastIndex to the end of it, and try the next pattern at exactly that spot. Without y, the engine might skip unknown characters and find a match later, which hides syntax errors in the input.
What should you keep in mind with /y (Sticky)?
It is similar to PHP's A modifier. Because the regex object carries state in lastIndex, create it inside the function that uses it, or reset lastIndex before each run. Sharing a sticky regex between calls is a reliable way to get bugs that only appear sometimes.
At a glance
| Category | Regex flags |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |