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