Languages
[Edit]
EN

JavaScript - flag y meaning in regex (sticky flag)

5 points
Created by:
DEX7RA
580

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 when lastIndex property 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

 

Alternative titles

  1. JavaScript - flag y meaning in RegExp (sticky flag)
  2. JavaScript - flag y meaning in regular expression (sticky flag)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join