Regex in JavaScript

Literal syntax, matchAll, replaceAll, and the indices flag.

  • javascript regex
  • matchAll
  • replaceAll
  • regexp
  • named groups js

Regex in JavaScript

Literal syntax, matchAll, replaceAll, and the indices flag.

Commands

CommandWhat it does
/pattern/giLiteral with flags
str.match with g flagAll matches, no group detail
str.matchAll with named groupsIterator with groups and indices
str.replaceAllLiteral global replace
d flag for indicesMatch start-end positions

Example

const re = /(?<y>\d{4})-(?<m>\d{2})/gd;
for (const m of '2026-10'.matchAll(re)) console.log(m.groups);

FAQ

match vs matchAll?

match with the g flag drops groups; matchAll keeps groups and indices - use matchAll for parsing.

How do I build patterns dynamically?

Use the RegExp constructor, but always escape user text first.

FAQ

match vs matchAll?
match with the g flag drops groups; matchAll keeps groups and indices - use matchAll for parsing.
How do I build patterns dynamically?
Use the RegExp constructor, but always escape user text first.

Regex