Skip to content

Modern RegExp features: named groups to v flag

  • The ES2018 additions: the s flag, named groups, lookbehind and Unicode property escapes.
  • The d flag (ES2022), the v flag (ES2024) and the ES2025 additions.
  • How they combine in a readable parser, and where each one bites.

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.

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.

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 sign
console.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 terminators
const 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 group
const m = /#(?<code>[A-Z]-\d+)/d.exec(line);
console.log(m.indices[0], m.indices.groups.code);

Output:

2026 11 18
Order #A-1042 shipped 18/11/2026 to Zoë, total €84.50
84.50
[ '#B-7' ]
false Leave at the door
[ 'Zoë', 'Müller' ]
[ 'Zo', 'M', 'ller' ]
[ 6, 13 ] [ 7, 13 ]

(?<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.

(?<=...) 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'.

With s, . also matches \n, \r, U+2028 and U+2029, replacing the [\s\S] workaround. It is unrelated to m, which changes ^ and $.

\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.

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.

v (unicodeSets) is an upgraded u: it adds set operations inside classes and properties of strings.

// v flag (ES2024): set operations and properties of strings
const greekLetters = /^[\p{Script=Greek}&&\p{Letter}]+$/v; // intersection
console.log(greekLetters.test('αβγ'), greekLetters.test('αβ1'));
const asciiNoVowels = /^[[a-z]--[aeiou]]+$/v; // subtraction
console.log(asciiNoVowels.test('rhythm'), asciiNoVowels.test('order'));
// \p{RGI_Emoji} matches whole emoji sequences, which u cannot do
console.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 class
try { 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 false
true false
8
2
SyntaxError
true
SyntaxError - 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 safely
const 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 alternatives
const 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 pattern
const 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\)
true
1042 7731
true true false
  • RegExp.escape(str) escapes syntax characters, and also a leading letter or digit and characters such as - and spaces as \x escapes, 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:...) turn i, m or s on or off for part of a pattern. Other flags are a SyntaxError inside a modifier.

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.

  • Shipping lookbehind to old Safari. Safari supported lookbehind only from 16.4 (released March 2023). A regex literal with lookbehind is a parse-time SyntaxError in older Safari, which breaks the whole script, not just one function.
  • Forgetting u or v with \p{...}. Without a Unicode flag, /\p{L}/ matches the letter p followed by {L}.
  • Assuming \w and \b are Unicode-aware. They remain ASCII-based with u and v. 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. Use RegExp.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 g or y regex. These keep lastIndex between calls, so re.test(s) can alternate between true and false. Create a new regex or reset lastIndex.
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.

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.

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.

  • 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.