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,

  1. We create a RegExp object regex with the 'd' flag /abc/d.
  2. We check the hasIndices property of regex to see if it is true.
  3. 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,

  1. We create a RegExp object regexWithD with the 'd' flag /abc/d.
  2. We create another RegExp object regexWithoutD without the 'd' flag /abc/.
  3. 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,

  1. We create a RegExp object regex with the 'd' flag /abc/d.
  2. We check the hasIndices property of regex in an if statement.
  3. 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.