JavaScript RegExp y Modifier

In JavaScript RegExp, ECMAScript 2015 (ES6) brought about the y (sticky) modifier which ensures that a regular expression has to match from only the lastIndex position of the target string and does not attempt to find further matches from subsequent positions. This last argument, an appropriate pointer to commence matching from, can be quite useful especially for parsing as well as tokenizing tasks where matches must be made in succession.

Syntax

/regexp/y

OR

new RegExp("regexp", "y")

Example 1: In the given below example y mode ensures that match starts from current lastIndex.

JavaScript
function example() {
    let str1 = "Hello world! Hello again!";
    let regex = /Hello/y;
    
    regex.lastIndex = 0;
    let match1 = regex.exec(str1);
    console.log("First match: " + match1[0] +
                " at index " + match1.index);
    
    // Move lastIndex to the space after "Hello"
    regex.lastIndex = 6;  
    let match2 = regex.exec(str1);
    console.log("Second match (should be null): " + match2);
    
     // Position to match the second "Hello"
    regex.lastIndex = 13; 
    let match3 = regex.exec(str1);
    console.log("Third match: " + match3[0] +
                " at index " + match3.index);
}
example();

Output
First match: Hello at index 0
Second match (should be null): null
Third match: Hello at index 13

Example 2: Here is a comparison of how y mode behaves with the g (global) modifier.

JavaScript
function example() {
    let str1 = "test1 test2 test3";
    
    let regexGlobal = /test\d/g;
    let matchGlobal;
    while (matchGlobal = regexGlobal.exec(str1)) {
        console.log("Global match: " + matchGlobal[0] +
                    " at index " + matchGlobal.index);
    }
    
    let regexSticky = /test\d/y;
    let matchSticky;
    while (matchSticky = regexSticky.exec(str1)) {
        console.log("Sticky match: " + matchSticky[0] +
                    " at index " + matchSticky.index);
    }
}
example();

Output
Global match: test1 at index 0
Global match: test2 at index 6
Global match: test3 at index 12
Sticky match: test1 at index 0

Supported Browsers

The RegExp y Modifier is supported by the following browsers:

  • Google Chrome
  • Apple Safari
  • Mozilla Firefox
  • Opera
  • Microsoft Edge


Contact Us