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.hasIndicesThis 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
regexwith the 'd' flag/abc/d. - We check the
hasIndicesproperty ofregexto 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
regexWithDwith the 'd' flag/abc/d. - We create another RegExp object
regexWithoutDwithout the 'd' flag/abc/. - We check the
hasIndicesproperty 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); // falseOutput
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
regexwith the 'd' flag/abc/d. - We check the
hasIndicesproperty ofregexin anifstatement. - 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.