Photo by PJH on Unsplash

On this page

This chapter follows JSON in JavaScript.

A RegExp describes a pattern; String methods run that pattern against text.

Literals and flags

/pattern/flags;
new RegExp("pattern", "flags");
Flag Meaning
g Global—exec/match find all
i Case insensitive
m Multiline ^ / $
s Dot matches newline (dotAll)
u Unicode code points
d Match indices (ES2022)
y Sticky—match only at lastIndex
/foo/gi.test("Foo bar"); // true

String methods

Method Use
str.match(re) First match or all with g
str.matchAll(re) Iterator of all matches (requires g)
str.search(re) Index of first match or -1
str.replace(re, repl) Replace first or all with g
str.replaceAll(re|str, repl) Replace all occurrences
str.split(re) Split on pattern
"2026-11-01".match(/(\d{4})-(\d{2})-(\d{2})/);
// ["2026-11-01", "2026", "11", "01", ...]

RegExp methods

const re = /a+/g;
re.exec("baaard"); // ["aa", index: 1, ...]
re.test("baa"); // true
re.lastIndex; // updated when /g or /y

Groups and lookaround (ES2018+)

const re = /(?<year>\d{4})-(?<month>\d{2})/;
const m = re.exec("2026-11");
m.groups.year; // "2026"

Lookbehind and lookahead assert context without consuming:

/(?<=\$)\d+/.exec("price $42"); // ["42"]
/(?!bad)\w+/.exec("good"); // ["good"]

Escaping user input (ES2025)

When building a pattern from arbitrary text, escape metacharacters:

RegExp.escape("a+b"); // literal safe fragment for `new RegExp(...)`

Prefer RegExp.escape over hand-rolled backslash rules when targeting current engines.

Practical notes

  • Unicode property escapes \p{Script=Latin} need the u flag.
  • ReDoS (catastrophic backtracking) is a real risk on user-supplied patterns and huge inputs—cap length or use dedicated parsers for untrusted data.
  • For JSON text, use JSON.parse, not regex—see the previous chapter.

Continue with Dates and Temporal.

Search articles

Type a word to search published articles.

Open the search page