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.stickyThis 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
regexwith the 'y' flag/abc/y. - We check the
stickyproperty ofregexto 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
regexWithYwith the 'y' flag/abc/y. - We create another RegExp object
regexWithoutYwithout the 'y' flag/abc/. - We check the
stickyproperty 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); // falseOutput
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
regexwith the 'y' flag/abc/y. - We check the
stickyproperty ofregexin anifstatement. - 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.