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,RegExp
class matches pattern only whenlastIndex
property indicates strat of expected sub-string directly.
Practical example:
xxxxxxxxxx
1
// indexes: 0 3
2
// | |
3
// v v
4
const string = 'abcd';
5
6
// pattern
7
// ||
8
// vv
9
const expression = /bc/y; // OR: new RegExp('bc', 'y');
10
11
expression.lastIndex = 0;
12
console.log(expression.test(string)); // false
13
14
expression.lastIndex = 1;
15
console.log(expression.test(string)); // true // OR: expression.exec(text) // ['bc']
16
17
expression.lastIndex = 2;
18
console.log(expression.test(string)); // false
19
20
expression.lastIndex = 3;
21
console.log(expression.test(string)); // false