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.
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.
RegExp.sticky returns value of type Boolean
.
In JavaScript, we can check if the 'y' flag is enabled for a RegExp object by accessing the sticky
property.
For example,
regex
with the 'y' flag /abc/y
.sticky
property of regex
to see if it is true.const regex = /abc/y;
const isStickyEnabled = regex.sticky;
console.log(isStickyEnabled);
true
In JavaScript, we can compare the sticky
property of RegExp objects with and without the 'y' flag.
For example,
regexWithY
with the 'y' flag /abc/y
.regexWithoutY
without the 'y' flag /abc/
.sticky
property of both objects and log the results to the console.const regexWithY = /abc/y;
const regexWithoutY = /abc/;
console.log(regexWithY.sticky); // true
console.log(regexWithoutY.sticky); // false
true false
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,
regex
with the 'y' flag /abc/y
.sticky
property of regex
in an if
statement.'Sticky searching is enabled.'
to the console; otherwise, we log 'Sticky searching is not enabled.'
.const regex = /abc/y;
if (regex.sticky) {
console.log('Sticky searching is enabled.');
} else {
console.log('Sticky searching is not enabled.');
}
Sticky searching is enabled.
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.