JavaScript RegExp sticky
Syntax & Examples
RegExp.sticky property
The sticky property of the RegExp object in JavaScript indicates whether the 'y' flag, which enables sticky searching, is set. This property is read-only.
Syntax of RegExp.sticky
The syntax of RegExp.sticky property is:
RegExp.prototype.sticky
This sticky property of RegExp whether or not the search is sticky. This property is read-only.
Return Type
RegExp.sticky returns value of type Boolean
.
✐ Examples
1 Checking if the sticky property is enabled
In JavaScript, we can check if the 'y' flag is enabled for a RegExp object by accessing the sticky
property.
For example,
- We create a RegExp object
regex
with the 'y' flag/abc/y
. - We check the
sticky
property ofregex
to see if it is true. - We log the result to the console.
JavaScript Program
const regex = /abc/y;
const isStickyEnabled = regex.sticky;
console.log(isStickyEnabled);
Output
true
2 Comparing sticky property with and without the 'y' flag
In JavaScript, we can compare the sticky
property of RegExp objects with and without the 'y' flag.
For example,
- We create a RegExp object
regexWithY
with the 'y' flag/abc/y
. - We create another RegExp object
regexWithoutY
without the 'y' flag/abc/
. - We check the
sticky
property of both objects and log the results to the console.
JavaScript Program
const regexWithY = /abc/y;
const regexWithoutY = /abc/;
console.log(regexWithY.sticky); // true
console.log(regexWithoutY.sticky); // false
Output
true false
3 Using sticky property in conditional statements
In JavaScript, we can use the sticky
property in conditional statements to perform different actions based on whether the 'y' flag is enabled.
For example,
- We create a RegExp object
regex
with the 'y' flag/abc/y
. - We check the
sticky
property ofregex
in anif
statement. - If the property is true, we log
'Sticky searching is enabled.'
to the console; otherwise, we log'Sticky searching is not enabled.'
.
JavaScript Program
const regex = /abc/y;
if (regex.sticky) {
console.log('Sticky searching is enabled.');
} else {
console.log('Sticky searching is not enabled.');
}
Output
Sticky searching is enabled.
Summary
In this JavaScript tutorial, we learned about sticky property of RegExp: the syntax and few working examples with output and detailed explanation for each example.