JavaScript Regex Cheat Sheet: Syntax, Flags and 15 Patterns
JavaScript regular expressions on one page: classes, anchors, groups, lookarounds and flags, 15 patterns to copy, and the gotchas to avoid.
Regular expressions look like line noise until you know the dozen or so pieces they're built from. After that, they're one of the most useful tools you have: validating input, searching logs, renaming hundreds of variables, cleaning up data.
This cheat sheet covers JavaScript's regex syntax, the flags, the string methods that use them, 15 ready-to-use patterns, and the gotchas (including the one that has taken down large websites). Every example works in the browser and in Node.js.
The syntax at a glance
Characters and classes
| Pattern | Matches |
|---|---|
abc | The exact text "abc" |
. | Any character except a line break (any character at all with the s flag) |
\d | A digit, 0–9 |
\w | A "word" character: A–Z, a–z, 0–9 and _ |
\s | Whitespace: spaces, tabs, line breaks, and Unicode spaces such as the non-breaking space |
\D, \W, \S | The opposite of \d, \w, \s |
[abc] | One of a, b or c |
[^abc] | Any character except a, b or c |
[a-z0-9] | A character in a range |
\p{L} | Any letter in any alphabet (needs the u flag) |
\. | A literal dot. Escape these with \: . * + ? ^ $ { } ( ) [ ] \ / and the pipe |
Note that \d and \w are ASCII-only, even with the u flag: \w doesn't match "é" or "ü". Use \p{L} (letters) and \p{N} (numbers) for international text.
Anchors and boundaries
| Pattern | Matches |
|---|---|
^ | The start of the string (of each line, with the m flag) |
$ | The end of the string (of each line, with the m flag) |
\b | A word boundary: between a \w character and a non-\w one |
\B | Anywhere that isn't a word boundary |
\bcat\b matches "cat" but not "category" or "concat".
Quantifiers
| Pattern | Means |
|---|---|
* | 0 or more |
+ | 1 or more |
? | 0 or 1 (optional) |
{3} | Exactly 3 |
{2,} | 2 or more |
{2,5} | Between 2 and 5 |
*?, +?, ?? | The same, but lazy: as few as possible |
Quantifiers are greedy by default: they take as much as they can. On <b>bold</b>, the pattern <.+> matches the whole string, while the lazy <.+?> matches just <b>.
Groups and alternation
| Pattern | Means |
|---|---|
(abc) | A capturing group: remembered as $1, match[1] |
(?:abc) | A non-capturing group: groups without remembering |
(?<year>\d{4}) | A named group: match.groups.year, $<year> |
\1, \k<year> | A backreference: the same text a group matched earlier |
cat|dog | Either "cat" or "dog" |
Lookarounds
Lookarounds check what's before or after a position without including it in the match:
| Pattern | Means | Example |
|---|---|---|
(?=…) | Followed by | \d+(?=px) matches "12" in "12px" |
(?!…) | Not followed by | \d+(?!\d|px) matches "30" in "12px 30em" |
(?<=…) | Preceded by | (?<=RM)\d+ matches "45" in "RM45" |
(?<!…) | Not preceded by | (?<!-)\b\d+ skips negative numbers |
Lookbehind ((?<=…), (?<!…)) works in every current browser; Safari added it in version 16.4.
Flags
| Flag | Name | Effect |
|---|---|---|
g | Global | Find every match, not just the first |
i | Ignore case | a matches "A" |
m | Multiline | ^ and $ match at each line's start and end |
s | Dot-all | . also matches line breaks |
u | Unicode | Treats emoji and other astral characters as one character; enables \p{…} |
v | Unicode sets | A stricter u with set operations in classes, like [\p{L}--[a-z]] |
y | Sticky | Matches only at lastIndex, useful for tokenisers |
d | Indices | Adds start and end positions for each group (match.indices) |
Using regexes in JavaScript
const date = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
// test: does it match?
date.test('Due 2026-10-29'); // true
// match: the first match, with its groups
const { year, month, day } = '2026-10-29'.match(date).groups;
// replace: groups can be used in the replacement
'2026-10-29'.replace(date, '$<day>/$<month>/$<year>'); // '29/10/2026'
// replace with a function, for anything computed
'hello regex world'.replace(/\b\w/g, (letter) => letter.toUpperCase()); // 'Hello Regex World'
// matchAll: every match with its groups (needs the g flag)
for (const match of 'Tags: #js #regex #web'.matchAll(/#(\w+)/g)) {
console.log(match[1]); // 'js', 'regex', 'web'
}
// split on a pattern
'a, b;c d'.split(/[,;\s]+/); // ['a', 'b', 'c', 'd']
Try each of these in the regex tester: it highlights the matches as you type, lists every group, and previews replacements.
15 patterns you can copy
These are practical patterns, not exhaustive validators. Test them against your real data.
| What | Pattern |
|---|---|
| Email (a sanity check) | ^[^\s@]+@[^\s@]+\.[^\s@]+$ |
| Malaysian mobile number (rough) | ^(?:\+?60|0)1\d-?\d{7,8}$ |
| Hex colour | ^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$ with i |
| ISO date (YYYY-MM-DD) | ^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$ |
| 24-hour time (HH:MM) | ^(?:[01]\d|2[0-3]):[0-5]\d$ |
| IPv4 address | ^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$ |
| UUID | ^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ with i |
| URL slug | ^[a-z0-9]+(?:-[a-z0-9]+)*$ |
| Semantic version | ^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$ |
| Password: 12+ characters with lower, upper and a digit | ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{12,}$ |
| Whole number, optionally negative | ^-?\d+$ |
| Decimal number | ^-?\d+(?:\.\d+)?$ |
| Trailing whitespace on each line | [ \t]+$ with gm |
| Repeated word ("the the") | \b(\w+)\s+\1\b with gi |
| HTML comment | <!--[\s\S]*?--> |
A few honest caveats:
- Email: no regex validates email addresses completely. The real test is sending a confirmation link. Use a loose check, like the one above, to catch typos.
- Dates: the ISO pattern accepts 2026-02-31. Check real dates with
Dateor a date library after the pattern passes. - URLs: parse them with
new URL(text)instead, inside atry. It handles every edge case a regex would miss. - Phone numbers: formats change. For anything serious, use a library such as libphonenumber.
- HTML: regexes are fine for quick searches, but use a real parser (
DOMParser, or a library) to change HTML.
Five gotchas
1. g makes test() remember where it stopped
A regex with the g (or y) flag keeps a lastIndex between calls:
const word = /cat/g;
word.test('cat'); // true, and lastIndex is now 3
word.test('cat'); // false: it started searching at position 3
Don't use g with test() on a shared regex, or reset word.lastIndex = 0 before each call.
2. Building a regex from user input
Characters like ., + and ( mean something in a pattern, so new RegExp(userInput) can match the wrong thing or throw. Escape the input first. Current browsers and Node.js 24 and later have RegExp.escape (Chrome 136, Firefox 134 and Safari 18.2):
const term = 'C++ (2026)';
const search = new RegExp(RegExp.escape(term), 'i');
// for older environments
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3. Catastrophic backtracking
Some patterns take exponential time on input that almost matches. The textbook example is (a+)+$ against "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa!": every extra "a" roughly doubles the work, and a few dozen characters can freeze a browser tab or a server.
This isn't theoretical. Badly backtracking regexes caused a 34-minute Stack Overflow outage in 2016 and a global Cloudflare outage in 2019. Attackers can do it on purpose, too (a "ReDoS" attack). To avoid it:
- Avoid nested quantifiers over the same characters, like
(a+)+,(\w*)*or(.*)*. - Avoid overlapping alternatives inside repeats, like
(\d|\d\d)+. - Be specific:
[^"]*instead of.*when you mean "anything up to the next quote". - Limit input length before running a regex on untrusted data.
The regex tester runs every pattern in a separate worker and stops it after 1.5 seconds, so you can safely try a pattern you're unsure about.
4. ^ and $ without the m flag
Without m, ^ and $ mean the start and end of the whole string. A pattern like ^\d+$ passes "123" but fails "123\n456". With m, it checks each line separately. Decide which you mean, especially when validating input that might contain line breaks.
5. Emoji and other characters outside the Basic Multilingual Plane
Without the u flag, JavaScript sees an emoji such as 🐉 as two separate "characters" (UTF-16 code units), so /^.$/.test('🐉') is false. With u, it's true. Use u (or v) whenever text might contain emoji or characters from other scripts.
Summary
- Learn the building blocks: classes (
\d,\w,[…]), anchors (^,$,\b), quantifiers (*,+,{n,m}), groups and lookarounds. - Use named groups and
matchAllfor readable code, theuflag for international text, andRegExp.escapefor user input. - Watch out for
lastIndexwithg, and for nested quantifiers that backtrack catastrophically.
Bookmark the regex tester and paste any pattern from this page into it: you'll see what it matches before it reaches your code.