VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-regexp-y-modifier/

⇱ JavaScript RegExp y Modifier - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript RegExp y Modifier

Last Updated : 4 Dec, 2024

In JavaScript, the y modifier is used in regular expressions for sticky matching, meaning the regular expression search will only start at the position where the last match ended.

Unlike other modifiers, the y modifier ensures that each match is found only if it starts at the exact position in the string, preventing the regex from skipping over characters. This makes it ideal when you need precise, non-overlapping matches in sequential searches.


Output
null
null
  • The first exec() call finds the first "o" in "hello", starting from the beginning.
  • The second exec() call fails to match because the y modifier enforces the search to continue only from the position immediately after the first "o". As a result, no further match is found.

Main Usages of the y Modifier

1. Sequential Matches Without Overlapping

The y modifier is ideal for matching multiple parts of a string in sequence, without allowing overlaps. Here’s an example:


Output
hello at position 0
hello at position 6
hello at position 12
  • The regex finds each occurrence of "o" one after another, starting at the position immediately after the previous match.
  • This ensures that each match is non-overlapping, even though there are multiple "o"s in the string.

2. Use with Anchors for Precise Matching

The y modifier works well with anchors like ^ and $ (start and end of the string), ensuring that the match is found precisely at the required position.


Output
[ 'hello', index: 0, input: 'hello123abc456', groups: undefined ]
lastIndex after 1st match: 5
null
lastIndex after 2nd match: 0

Advantages of Using the y Modifier

  • Precise Matching: It ensures that matches occur only at specific positions, avoiding re-scanning or skipping over parts of the string.
  • Non-Overlapping Matches: Useful when you need to capture multiple instances of a pattern sequentially without overlapping.
  • Efficient for Parsing: It’s ideal for tokenizing text or structured data where precise, sequential matching is required.
Comment