Modern RegExp features: named groups to v flag
What you’ll learn
Section titled “What you’ll learn”- The ES2018 additions: the
sflag, named groups, lookbehind and Unicode property escapes. - The
dflag (ES2022), thevflag (ES2024) and the ES2025 additions. - How they combine in a readable parser, and where each one bites.
Summary
Section titled “Summary”TL;DR: JavaScript regular expressions gained most of their modern features in ES2018 (s flag, (?<name>...) groups, (?<=...) and (?<!...) lookbehind, \p{...} property escapes). ES2022 added the d flag for match indices, ES2024 the v flag, and ES2025 RegExp.escape(), duplicate named groups and (?i:...) modifiers. ES2026 added no new regex features. Everything up to ES2024 runs on Node.js 22; the ES2025 features need Node.js 24 or a current browser.
The problem it solves
Section titled “The problem it solves”Before ES2018, groups were only numbered (match[3]), so adding one shifted every later index. . never matched a newline, there was no lookbehind, and \w only knew ASCII, so names like Zoë broke validation.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. Outputs were produced with Node.js 22.23 unless a sample says otherwise.
How it works
Section titled “How it works”The first sample covers the ES2018 features and the d flag on one OrdersPortal status line:
const line = 'Order #A-1042 shipped 2026-11-18 to Zoë, total €84.50';
// Named groups (ES2018)const date = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;const { year, month, day } = line.match(date).groups;console.log(year, month, day);console.log(line.replace(date, '$<day>/$<month>/$<year>'));
// Lookbehind (ES2018): the amount after a currency sign, without the signconsole.log(line.match(/(?<=€)\d+(?:\.\d{2})?/)[0]);console.log('Order #A-1042, ref #B-7'.match(/(?<!Order )#[A-Z]-\d+/g)); // negative lookbehind
// s (dotAll) flag (ES2018): . also matches line terminatorsconst note = 'Gift note:\nLeave at the door';console.log(/note:.(.+)/.test(note), note.match(/note:.(.+)/s)[1]);
// Unicode property escapes (ES2018, needs u or v)console.log('Zoë Müller'.match(/\p{L}+/gu));console.log('Zoë Müller'.match(/\w+/g)); // \w is ASCII-only, even with u
// d flag (ES2022): start and end indices of the match and of each groupconst m = /#(?<code>[A-Z]-\d+)/d.exec(line);console.log(m.indices[0], m.indices.groups.code);Output:
2026 11 18Order #A-1042 shipped 18/11/2026 to Zoë, total €84.5084.50[ '#B-7' ]false Leave at the door[ 'Zoë', 'Müller' ][ 'Zo', 'M', 'ller' ][ 6, 13 ] [ 7, 13 ]Named capture groups (ES2018)
Section titled “Named capture groups (ES2018)”(?<name>...) adds a groups object (with a null prototype) to the match. \k<name> refers back to a group inside the pattern, $<name> inserts it in a replace string, and a replacer function receives groups as its last argument. A group that did not participate is undefined, so destructuring defaults work.
Lookbehind assertions (ES2018)
Section titled “Lookbehind assertions (ES2018)”(?<=...) requires, and (?<!...) forbids, text immediately before the current position, without consuming it. Unlike many engines, JavaScript allows variable-length lookbehind such as (?<=\$\d+). The lookbehind is matched right to left, so greedy captures inside it split differently from what you might expect: /(?<=(\d+)(\d+))$/.exec('1053') captures '1' and '053'.
The s (dotAll) flag (ES2018)
Section titled “The s (dotAll) flag (ES2018)”With s, . also matches \n, \r, U+2028 and U+2029, replacing the [\s\S] workaround. It is unrelated to m, which changes ^ and $.
Unicode property escapes (ES2018)
Section titled “Unicode property escapes (ES2018)”\p{...} matches by Unicode property, such as \p{L} (letters), \p{N} (numbers) or \p{Script=Greek}; \P{...} negates. It requires the u or v flag. Note that \w, \d and \b stay ASCII-based even with u (with u plus i, \w also matches two non-ASCII characters, ſ and the Kelvin sign). For more on code points and graphemes, see Unicode Support.
Match indices: the d flag (ES2022)
Section titled “Match indices: the d flag (ES2022)”d (hasIndices) adds an indices array of [start, end] pairs for the match and every group, plus indices.groups. It is useful for highlighting or editor tooling. Engines must compute and allocate the extra arrays, so enable it only when you need positions.
The v flag (ES2024)
Section titled “The v flag (ES2024)”v (unicodeSets) is an upgraded u: it adds set operations inside classes and properties of strings.
// v flag (ES2024): set operations and properties of stringsconst greekLetters = /^[\p{Script=Greek}&&\p{Letter}]+$/v; // intersectionconsole.log(greekLetters.test('αβγ'), greekLetters.test('αβ1'));
const asciiNoVowels = /^[[a-z]--[aeiou]]+$/v; // subtractionconsole.log(asciiNoVowels.test('rhythm'), asciiNoVowels.test('order'));
// \p{RGI_Emoji} matches whole emoji sequences, which u cannot doconsole.log('👩👩👧 ok'.match(/^\p{RGI_Emoji}/v)[0].length);console.log('👩👩👧 ok'.match(/^\p{Emoji}/u)[0].length);
// v is stricter: some characters must be escaped inside a classtry { new RegExp('[(]', 'v'); } catch (e) { console.log(e.constructor.name); }console.log(new RegExp('[\\(]', 'v').test('('));try { new RegExp('a', 'uv'); } catch (e) { console.log(e.constructor.name, '- u and v cannot be combined'); }Output:
true falsetrue false82SyntaxErrortrueSyntaxError - u and v cannot be combined\p{RGI_Emoji} matches the whole eight-unit family emoji; \p{Emoji} matches only its first code point. In v mode, characters such as (, [, {, /, - and | must be escaped inside a class, so switching a u pattern to v can throw: test each one.
ES2025: RegExp.escape, duplicate named groups and modifiers
Section titled “ES2025: RegExp.escape, duplicate named groups and modifiers”This sample needs Node.js 24 or later (run with Node.js 24.22, V8 13.6). On Node.js 22 the duplicate group name is a SyntaxError.
// ES2025 RegExp features. Needs Node.js 24 or later (V8 13.6+).
// RegExp.escape: build a pattern from user input safelyconst search = 'USB-C (2 m)';const re = new RegExp(RegExp.escape(search), 'i');console.log(RegExp.escape(search));console.log(re.test('Braided usb-c (2 m) cable'));
// Duplicate named groups in different alternativesconst orderRef = /ORD-(?<id>\d+)|(?<id>\d+)-WEB/;console.log('ORD-1042'.match(orderRef).groups.id, '7731-WEB'.match(orderRef).groups.id);
// Pattern modifiers: case-insensitive only for part of the patternconst sku = /^(?i:sku)-[A-Z]{3}$/;console.log(sku.test('sku-ABC'), sku.test('SKU-ABC'), sku.test('sku-abc'));Output:
\x55SB\x2dC\x20\(2\x20m\)true1042 7731true true falseRegExp.escape(str)escapes syntax characters, and also a leading letter or digit and characters such as-and spaces as\xescapes, so the result is safe in any position of a larger pattern.- Duplicate named groups are allowed only in different alternatives, where at most one can participate in a match.
- Modifiers
(?flags:...)or(?flags-flags:...)turni,morson or off for part of a pattern. Other flags are aSyntaxErrorinside a modifier.
Realistic example
Section titled “Realistic example”OrdersPortal parses carrier status emails. Named groups keep the parser readable, s lets the free-text note span lines, d records where the status was found for highlighting in the support UI, and a lookbehind extracts amounts without their currency symbols:
// carrier-updates.mjs - parse carrier status emails for OrdersPortal shipments.const STATUS = new RegExp( String.raw`^Shipment (?<tracking>[A-Z]{2}\d{9}[A-Z]{2})` + // named group String.raw` for order #(?<order>[A-Z]-\d+)` + String.raw` is (?<status>delivered|in transit|delayed)` + String.raw`(?: \(ETA (?<eta>\d{4}-\d{2}-\d{2})\))?` + String.raw`(?:\nNote: (?<note>.*))?$`, // with s, the note may span lines 'dsu',);
export function parseUpdate(text) { const match = STATUS.exec(text.normalize('NFC')); if (!match) return null; const { tracking, order, status, eta = null, note = null } = match.groups; return { tracking, order, status, eta, note, statusAt: match.indices.groups.status };}
// Amounts after a currency symbol, without capturing the symbol (lookbehind).export const amounts = (text) => text.match(/(?<=[$€£])\d+(?:\.\d{2})?/g) ?? [];
console.log(parseUpdate('Shipment RA123456785DE for order #A-1042 is delayed (ETA 2026-11-21)\nNote: Customs check.\nCall Zoë before delivery.'));console.log(parseUpdate('Shipment RA987654321DE for order #B-7 is delivered'));console.log(parseUpdate('Shipment ??? for order #B-7 is lost'));console.log(amounts('Duties €12.40 and $3 handling, ref 4411'));Output:
{ tracking: 'RA123456785DE', order: 'A-1042', status: 'delayed', eta: '2026-11-21', note: 'Customs check.\nCall Zoë before delivery.', statusAt: [ 44, 51 ]}{ tracking: 'RA987654321DE', order: 'B-7', status: 'delivered', eta: null, note: null, statusAt: [ 41, 50 ]}null[ '12.40', '3' ]String.raw pieces let each line carry a comment, and optional groups map to null through destructuring defaults. To iterate over every match, use matchAll.
Common mistakes
Section titled “Common mistakes”- Shipping lookbehind to old Safari. Safari supported lookbehind only from 16.4 (released March 2023). A regex literal with lookbehind is a parse-time
SyntaxErrorin older Safari, which breaks the whole script, not just one function. - Forgetting
uorvwith\p{...}. Without a Unicode flag,/\p{L}/matches the letterpfollowed by{L}. - Assuming
\wand\bare Unicode-aware. They remain ASCII-based withuandv. Use\p{L},\p{N}or explicit classes. - Concatenating user input into a pattern.
new RegExp(userText)breaks on(or.and opens the door to ReDoS. UseRegExp.escape(), or a manual escaper on older runtimes. - Catastrophic backtracking. Nested quantifiers such as
(a+)+$can take exponential time on hostile input. Bound input length, keep patterns linear, and test with long non-matching strings. - Reusing a
goryregex. These keeplastIndexbetween calls, sore.test(s)can alternate betweentrueandfalse. Create a new regex or resetlastIndex.
When to use it and when not to
Section titled “When to use it and when not to”| Feature | Edition | Use it for |
|---|---|---|
s flag |
ES2018 | . across lines |
| Named groups | ES2018 | any pattern with more than one or two groups |
| Lookbehind | ES2018 | context before a match without consuming it |
\p{...} |
ES2018 | international letters, scripts, emoji |
d flag |
ES2022 | highlighting, editor and lint tooling |
v flag |
ES2024 | set operations, emoji sequences; prefer it over u in new code |
RegExp.escape, duplicate names, modifiers |
ES2025 | safe dynamic patterns, alternative formats, partial case-insensitivity |
Regex is the wrong tool for nested formats (HTML, JSON), for URL parsing (use URL), and for anything startsWith or split handle clearly.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data:
| Feature | Chrome | Firefox | Safari | Node.js |
|---|---|---|---|---|
s flag |
62 | 78 | 11.1 | 8.10.0 |
| Named groups | 64 | 78 | 11.1 | 10.0.0 |
| Lookbehind | 62 | 78 | 16.4 | 8.10.0 |
\p{...} |
64 | 78 | 11.1 | 10.0.0 |
d flag |
90 | 88 | 15 | 16.0.0 |
v flag |
112 | 116 | 17 | 20.0.0 |
| Duplicate named groups | 125 | 129 | 17 | 23.0.0 |
| Modifiers | 125 | 132 | 26 | 23.0.0 |
RegExp.escape |
136 | 134 | 18.2 | 24.0.0 |
Edge matches Chrome (from Edge 79 for the ES2018 features). Safari on iOS matches desktop Safari except where iOS 11.3 is listed for the ES2018 features. Deno 1.44+ supports everything except RegExp.escape (Deno 2.3.2); Bun 1.2.3+ supports all of it. Internet Explorer supports none.
New regex syntax cannot be polyfilled at run time. Transpilers can rewrite some of it for older targets (Babel’s preset-env includes plugins for the s flag, named and duplicate named groups, \p{...}, the v flag and modifiers, with limits), but lookbehind cannot be rewritten. RegExp.escape is a plain function and can be polyfilled.
Interview questions
Section titled “Interview questions”1. What does the s flag change, and how is it different from m?
s makes . match line terminators. m makes ^ and $ match at line boundaries. They are independent and often used together.
2. Why prefer named groups over numbered ones?
The code reads by meaning (groups.order), and adding a group does not shift other references. They also work in replacements ($<name>) and backreferences (\k<name>).
3. What is the difference between u and v?
v includes everything u does and adds set intersection and subtraction in classes, nested classes, string literals in classes and properties of strings such as \p{RGI_Emoji}. Its class syntax is stricter, and the two flags cannot be combined.
4. Senior scenario: OrdersPortal lets support agents search order notes with keywords, and must support all languages and run on browsers from the last few years. How do you design it?
Escape the query with RegExp.escape (or a vetted fallback) and cap its length. Normalize notes and query the same way (NFD with combining marks removed for accent-insensitive matching), and use \p{...} with u instead of \w. Keep lookbehind and ES2025 syntax out of shipped literals, or build them with a feature-detected new RegExp() so a failure stays local. For large data sets, use a server-side full-text index instead.
Key takeaways
Section titled “Key takeaways”- ES2018 made JavaScript regexes practical:
s, named groups, lookbehind and\p{...}. d(ES2022) adds match positions;v(ES2024) adds set operations and emoji sequences and is the better default for new Unicode-aware patterns.- ES2025 added
RegExp.escape, duplicate named groups and modifiers; they need Node.js 24 or a 2025-era browser. - Unsupported regex syntax breaks the whole script, so check your support matrix.
Related pages
Section titled “Related pages”- Regular expressions: the basics of patterns, flags and methods.
- String.matchAll: iterate over every match with its groups.
- Unicode Support: code points, graphemes and normalization.
- Template Literals:
String.rawfor readable pattern pieces. - Destructuring: unpack
match.groupswith defaults.
Official references
Section titled “Official references”- ECMAScript Language Specification, Patterns, Pattern flags and
RegExp.escape(current draft) - TC39 proposals: s flag, named groups, lookbehind, property escapes, match indices, v flag, RegExp.escape, duplicate named groups, modifiers
- MDN: Regular expressions guide
- MDN: Named capturing group, Lookbehind assertion, Unicode character class escape and Modifier
- MDN: RegExp.prototype.dotAll, hasIndices, unicodeSets and RegExp.escape()