EN
JavaScript - flag y meaning in regex (sticky flag)
5
points
In this short article, we would like to explain flag y meaning in regular expression in JavaScript.
Qucik solution:
When the
y(sticky) flag is used,RegExpclass matches pattern only whenlastIndexproperty indicates strat of expected sub-string directly.
Practical example:
// ONLINE-RUNNER:browser;
// indexes: 0 3
// | |
// v v
const string = 'abcd';
// pattern
// ||
// vv
const expression = /bc/y; // OR: new RegExp('bc', 'y');
expression.lastIndex = 0;
console.log(expression.test(string)); // false
expression.lastIndex = 1;
console.log(expression.test(string)); // true // OR: expression.exec(text) // ['bc']
expression.lastIndex = 2;
console.log(expression.test(string)); // false
expression.lastIndex = 3;
console.log(expression.test(string)); // false