A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-regexp-hasindices-property/ below:

JavaScript RegExp hasIndices Property - GeeksforGeeks

JavaScript RegExp hasIndices Property

Last Updated : 05 Aug, 2025

The hasIndices property in JavaScript regular expressions indicates whether the d (indices) flag is enabled. When the d flag is set, the regular expression captures the start and end indices of the matched substring within the input string, providing detailed positional information.

JavaScript
// Regular expression without 'd' flag
let regex1 = /test/;
console.log(regex1.hasIndices);

// Regular expression with 'd' flag
let regex2 = /test/d;
console.log(regex2.hasIndices);
Syntax:
regex.hasIndices
Key Points Real-World Examples of the hasIndices Property 1. Capturing Match Indices JavaScript
let s = "JavaScript is fun";
let regex = /is/d;

let match = regex.exec(s);
console.log(match.indices); 

The d flag captures the indices of "is" as [11, 13], representing the start and end positions.

2. Using Indices with Groups JavaScript
let s = "color: blue; background: red;";
let regex = /(\w+): (\w+)/d;

let match = regex.exec(s);
console.log(match.indices); 

Here, the d flag captures indices for the entire match and each capturing group:

3. Iterating Over Matches JavaScript
let s = "apple banana cherry";
let regex = /\w+/gd;

let match;
while ((match = regex.exec(s)) !== null) {
    console.log(`Matched: ${match[0]}, Indices: ${match.indices[0]}`);
} 

The d flag allows for precise positional logging during iteration.

4. Validating Position-Based Rules JavaScript
let s = "abc123xyz";
let regex = /\d+/d;

let match = regex.exec(s);
if (match.indices[0][0] > 3) {
    console.log("Numbers found after 3rd character");
}

The d flag helps validate if a pattern occurs after a specific position.

5. Parsing CSV Data with Indices JavaScript
let csv = "name,age,location";
let regex = /[^,]+/gd;

let match;
while ((match = regex.exec(csv)) !== null) {
    console.log(`Matched: ${match[0]} at indices: ${match.indices[0]}`);
}

The d flag ensures efficient tracking of where each field occurs in the CSV string.

Why Use the hasIndices Property? Conslusion

The hasIndices property is a powerful tool for developers working with advanced regular expression-based parsing and analysis, adding an extra layer of flexibility and precision to pattern matching.

Recommended Links:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4