Jarede
Jarede

Reputation: 3498

javascript regex matches with g flag but not y flag

I'm having trouble understanding why this is returning true

let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = new RegExp(/\(/g);
reg.test(str);

yet

let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = new RegExp(/\(/y);
reg.test(str);

is returning false.

Adding the global flag to the sticky flag doesn't help either.

Upvotes: 0

Views: 226

Answers (2)

revo
revo

Reputation: 48741

Sticky flag y starts matching at position 0 (reading from lastIndex property). There is no ( left at that position in str so your second match try fails.

Sticky flag from MDN:

matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes)

Upvotes: 1

Marcos Casagrande
Marcos Casagrande

Reputation: 40434

Adding the global flag to the sticky flag doesn't help either.

A regular expression defined as both sticky and global ignores the global flag.

The "y" flag indicates that it matches only from the index indicated by the lastIndex

You must set the lastIndex property of the regex, it defaults to 0, and there isn't any ( at that index, that's why nothing is matched. The ( appears at index 5.

let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = /\(/y; // No need for new RegExp

reg.lastIndex = str.indexOf('('); // 5
reg.test(str); // True

More on sticky flag here:

Upvotes: 2

Related Questions