JS RegExp Groups
In this page:
(pattern) // capturing group
(?:pattern) // non-capturing
(?<name>pattern) // named group
Basic Capturing Groups
Wrapping part of a pattern in parentheses, like (\d{3})-(\d{4}), captures each parenthesized section separately -- calling .match() on a matching string returns an array where index 0 is the full match, and each following index corresponds to one captured group, in order.
उदाहरण: Basic Capturing Groups
const match = "555-1234".match(/(\d{3})-(\d{4})/);
console.log(match[0], match[1], match[2]);
Non-Capturing Groups: (?:...)
A non-capturing group, written (?:pattern), groups part of a pattern (for applying a quantifier, or organizing alternation) without adding an entry to the array of captured results -- useful when you need grouping purely for structure, not for extracting that piece separately.
उदाहरण: Non-Capturing Groups: (?:...)
const match = "abcabc".match(/(?:abc)+/);
console.log(match[0]); // grouped for the +, but not captured separately
Named Capturing Groups: (?<name>...)
Instead of referencing a captured group by its numeric position, (?<name>pattern) assigns it a readable name, accessible afterward via match.groups.name -- making code that works with several captured pieces significantly clearer than relying on numbered positions.
उदाहरण: Named Capturing Groups: (?<name>...)
const match = "2024-06-15".match(/(?<year>\d{4})-(?<month>\d{2})/);
console.log(match.groups.year, match.groups.month);
Backreferences: Reusing a Captured Group
A backreference, written \1 (or \k<name> for a named group), refers back to whatever a previous group in the same pattern actually matched -- useful for finding repeated content, like a word that appears twice in a row, without hardcoding what that repeated content actually is.
उदाहरण: Backreferences: Reusing a Captured Group
console.log(/(\w+) \1/.test("hello hello")); // true, same word repeated
A Practical Example: Parsing a Full Name
Combining named capturing groups with a realistic pattern -- extracting a first and last name from a full name string, or breaking a URL into its component parts -- illustrates how groups turn a single matched pattern into several individually usable pieces of extracted data.
उदाहरण: A Practical Example: Parsing a Full Name
const match = "Sam Sharma".match(/(?<first>\w+) (?<last>\w+)/);
console.log(match.groups.first, match.groups.last);
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML