All articles

JavaScript regex cheat sheet

· 5 min read

Regular expressions are a small language of their own, and JavaScript's flavor has a few features and traps that differ from Python, PCRE or grep. This cheat sheet covers the syntax you'll use daily, the string methods that consume it, and the mistakes that cause most regex bugs.

Creating a regex

const literal = /colou?r/i;                 // literal: compiled once, no escaping of quotes
const dynamic = new RegExp(`^${prefix}\\d+$`, "g"); // from a string: backslashes must be doubled

Use a literal when the pattern is fixed. Use new RegExp() only when part of the pattern comes from a variable, and escape that part if it's user input.

Characters and classes

Syntax Matches
. Any character except line terminators (any character with the s flag)
\d / \D ASCII digit / not a digit
\w / \W [A-Za-z0-9_] / anything else
\s / \S Whitespace (spaces, tabs, line breaks, Unicode spaces) / not whitespace
[abc] One of a, b or c
[^abc] Any character except a, b or c
[a-z0-9] A range
\p{L} Any letter in any script (needs the u or v flag)
\. \* \\ A literal dot, asterisk or backslash

Inside a character class, most special characters lose their meaning: [.] is a literal dot. Only ], \, ^ (at the start) and - (between characters) need care.

Anchors and boundaries

Syntax Matches
^ Start of the string (start of each line with m)
$ End of the string (end of each line with m)
\b Word boundary, between \w and \W
\B Not a word boundary

Validation patterns almost always need both anchors. /\d{5}/ accepts abc123456xyz; /^\d{5}$/ doesn't.

Quantifiers

Syntax Meaning
* 0 or more
+ 1 or more
? 0 or 1
{3} Exactly 3
{2,} 2 or more
{2,5} Between 2 and 5
*? +? ?? {2,5}? Lazy versions: as few as possible

Quantifiers are greedy by default:

'<b>bold</b> and <i>italic</i>'.match(/<.+>/)[0];  // '<b>bold</b> and <i>italic</i>'
'<b>bold</b> and <i>italic</i>'.match(/<.+?>/)[0]; // '<b>'

Groups and references

Syntax Meaning
(abc) Capturing group
(?:abc) Non-capturing group
(?<year>\d{4}) Named capturing group
\1, \k<year> Backreference to a group inside the pattern
`a b`
$1, $<year> Group reference in a replace() replacement string

Named groups make code easier to read:

const { year, month, day } = "2026-10-22".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/).groups;

"2026-10-22".replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, "$<d>/$<m>/$<y>"); // '22/10/2026'

Lookahead and lookbehind

These check what comes before or after a position without including it in the match:

Syntax Meaning
x(?=y) x followed by y
x(?!y) x not followed by y
(?<=y)x x preceded by y
(?<!y)x x not preceded by y
"Price: $42, tax: $3".match(/(?<=\$)\d+/g);          // ['42', '3']
"1234567".replace(/\B(?=(\d{3})+(?!\d))/g, ",");      // '1,234,567'
/^(?=.*\d)(?=.*[a-z]).{8,}$/.test("password1");       // true: has a digit and a letter, 8+ chars

Flags

Flag Name Effect
g global Find all matches; exec() and test() track lastIndex
i ignoreCase Case-insensitive
m multiline ^ and $ match at line breaks
s dotAll . also matches line breaks
u unicode Full Unicode: code points, \p{...}, stricter syntax
v unicodeSets Like u, plus set operations in classes ([\p{L}--[a-z]])
y sticky Match only at lastIndex
d hasIndices Adds start and end positions of groups to results

String and RegExp methods

Method Returns Notes
re.test(str) true / false Stateful with g or y
str.match(re) First match with groups, or all matches without groups when g is set null when nothing matches
str.matchAll(re) Iterator of every match with groups Requires the g flag
str.replace(re, x) New string Replaces the first match unless g is set
str.replaceAll(re, x) New string Requires the g flag when given a regex
str.split(re) Array Captured groups are included in the result
str.search(re) Index or -1 Ignores g

When you need every match and its groups, matchAll is the clean choice:

const text = "id=7 id=12 id=40";
for (const m of text.matchAll(/id=(\d+)/g)) {
  console.log(m[1], m.index); // '7' 0, '12' 5, '40' 11
}

A function as the replacement gets the match and groups:

"hello world".replace(/\b\w/g, (letter) => letter.toUpperCase()); // 'Hello World'

Common mistakes

Reusing a global regex with test()

const re = /a/g;
re.test("a"); // true  (lastIndex is now 1)
re.test("a"); // false (search starts at index 1)

Drop g when you only need a yes or no.

Forgetting to escape the dot

/example.com/ also matches exampleXcom. Write /example\.com/.

Double escaping in new RegExp

In a string, "\d" is just "d". Write new RegExp("\\d+"), or use a literal.

Catastrophic backtracking

Nested quantifiers on overlapping patterns, such as /^(a+)+$/ or /^(\w+\s?)*$/, can take exponential time on input that almost matches. On a server, a crafted string can block the event loop (a ReDoS attack). Avoid nested quantifiers, make alternatives mutually exclusive and limit input length before matching.

Expecting a regex to do everything

Some formats can't be fully validated with a regex. For email, a simple pattern plus a confirmation email is better than a 400-character expression; for URLs, new URL() parses more reliably. The ready-made patterns for email, URL, phone number, password, IP address and date explain where each one stops being reliable.

Quick recipes

/^\s+|\s+$/g                         // trim (or just use str.trim())
/\s+/g                               // collapse whitespace: str.replace(/\s+/g, " ")
/^[a-z0-9]+(?:-[a-z0-9]+)*$/         // URL slug
/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i     // hex color
/^\d{4}-\d{2}-\d{2}$/                // YYYY-MM-DD shape (not a valid-date check)
/[\u{1F300}-\u{1FAFF}]/u             // many emoji (a range, not a complete list)

When a pattern builds HTML from matched text, escape the output; escaping HTML in JavaScript explains why.

Frequently asked questions

Why does my regex with the g flag match only every other time?

A global or sticky regex remembers lastIndex between test() and exec() calls. Reusing the same object on new strings starts from the old position. Create a new regex, reset lastIndex = 0, or drop the g flag for test().

Does JavaScript support lookbehind?

Yes. (?<=...) and (?<!...) are part of ES2018 and work in all current browsers and Node.js.

How do I escape user input for use in a regex?

Escape the special characters with str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"). Newer engines also provide RegExp.escape().

Is there a difference between \d and [0-9]?

In JavaScript, no: \d matches only ASCII digits, even with the u flag. Use \p{Nd} with the u flag for digits in other scripts.

Further reading