The ‘y’ Flag


The 'y' flag specifies that the match must happen at the beginning of the string or at the character immediately following the previous match. Find all matches of ‘abc’ using the ‘y’ flag

let wordPttn = /abc/gy
let targetString = "abcabcxyxabc";
let results = targetString.matchAll(wordPttn);
for (let result of results) {
console.log(result[0]);
}

Output:

abc
abc

As you can see from the output above, the pattern /abc/gy will only match the first two ‘abc‘ sequences in the input string ‘abcabcxyxabc‘, because the second ‘abc‘ starts immediately after the first ‘abc‘ just like the ‘y‘ flag requires it to. It will not match the third ‘abc‘ as it does not start immediately at the next index in the input string after the second ‘abc‘.