Home >Web Front-end >JS Tutorial >How Do I Access Captured Subgroups in JavaScript Regular Expressions?

How Do I Access Captured Subgroups in JavaScript Regular Expressions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 12:12:20912browse

How Do I Access Captured Subgroups in JavaScript Regular Expressions?

Accessing Matched Groups in JavaScript Regular Expressions

When matching a string against a regular expression, it's crucial to understand how to retrieve the captured subgroups. In JavaScript, this is achieved using capturing groups within the regular expression.

Consider the following example:

var myString = "something format_abc"; // Target substring: "abc"

var arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);

console.log(arr); // [" format_abc", "abc"]
console.log(arr[1]); // undefined
console.log(arr[0]); // format_undefined

Reason for Undefined Output:

While the regular expression correctly matches the substring "abc," accessing arr[1] returns undefined due to incorrect printing in the console.log statements. console.log interprets the string %A as a formatting placeholder and attempts to substitute it with the second parameter, which is undefined in this case.

Accessing Matched Groups:

To extract the matched group, use arr[1]. This will correctly return "abc."

Iterating Over Multiple Matches (ES2020):

JavaScript 2020 introduced the matchAll method, which yields an iterator that can be used to iterate over all matches in a string.

const string = "something format_abc";
const regexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
const matches = string.matchAll(regexp);

for (const match of matches) {
  console.log(match);
  console.log(match.index);
}

This approach provides a cleaner and more intuitive way to handle multiple matches.

The above is the detailed content of How Do I Access Captured Subgroups in JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn