Regex Sticky Flag
Regular Expressions: Regex Sticky Flag
What does the regex flag ‘Y’ do in regular expressions?
View Answer:
Interview Response: The flag y allows us to perform the search at the given position in the source string. The flag y makes regexp.exec(str) search strictly at position lastIndex, not “starting from” it. There is a critical performance gain when using flag y.
Code Example:
let str = 'let varName = "value"';
let regexp = /\w+/y;
regexp.lastIndex = 3;
alert(regexp.exec(str)); // null (there's a space at position 3, not a word)
regexp.lastIndex = 4;
alert(regexp.exec(str)); // varName (word at position 4)