JavaScript Regular Expressions: A Practical Guide
Regex is powerful and easy to get wrong. Learn the syntax, the flags, the common patterns, and how to test them safely.
By Velloreth
The basics
A regex is a pattern between slashes, with optional flags after.
const pattern = /hello/i;
Creating
const literal = /abc/;
const constructed = new RegExp('abc');
const dynamic = new RegExp(userInput, 'g');
Use a literal when the pattern is fixed, and the constructor when it is built from a variable.
Flags
| Flag | Meaning |
|---|---|
g | Global — find all matches |
i | Case-insensitive |
m | Multiline — ^ and $ match line boundaries |
s | Dotall — . matches newlines |
u | Unicode — proper code point handling |
y | Sticky — match only at lastIndex |
d | Indices — include match positions |
Methods
test
Returns a boolean.
/^\d+$/.test('12345'); // true
/^\d+$/.test('12a45'); // false
The fastest way to check for a match.
match
Returns the match, or null.
'hello world'.match(/\w+/); // ['hello']
'hello world'.match(/\w+/g); // ['hello', 'world']
With capture groups:
const result = '2026-10-26'.match(/(\d{4})-(\d{2})-(\d{2})/);
result[0]; // '2026-10-26'
result[1]; // '2026'
result[2]; // '10'
result[3]; // '26'
matchAll
Returns an iterator of all matches with their groups. Requires the g flag.
const text = 'a1 b2 c3';
for (const match of text.matchAll(/([a-z])(\d)/g)) {
console.log(match[1], match[2]);
}
replace
Substitutes matches.
'hello world'.replace('world', 'there'); // 'hello there'
'hello world'.replace(/o/g, '0'); // 'hell0 w0rld'
With a function:
'2026-10-26'.replace(/(\d{4})-(\d{2})-(\d{2})/, (_, y, m, d) => `${d}/${m}/${y}`);
// '26/10/2026'
replaceAll
Replaces all occurrences without needing the g flag.
'a-b-c'.replaceAll('-', '_'); // 'a_b_c'
split
'a,b;c'.split(/[,;]/); // ['a', 'b', 'c']
search
Returns the index of the first match, or -1.
'hello'.search(/l/); // 2
exec
Stateful matching with the g flag.
const re = /\d+/g;
const text = 'a1 b22 c333';
let m;
while ((m = re.exec(text)) !== null) {
console.log(m[0], m.index);
}
Character classes
| Pattern | Matches |
|---|---|
. | Any character except newline |
\d | Digit |
\D | Not a digit |
\w | Word character (letter, digit, underscore) |
\W | Not a word character |
\s | Whitespace |
\S | Not whitespace |
[abc] | Any of a, b, c |
[^abc] | Not a, b, or c |
[a-z] | Range |
[a-zA-Z0-9] | Multiple ranges |
Quantifiers
| Pattern | Meaning |
|---|---|
* | Zero or more |
+ | One or more |
? | Zero or one |
{3} | Exactly three |
{3,} | Three or more |
{3,5} | Between three and five |
*? | Zero or more, lazy |
+? | One or more, lazy |
Greedy quantifiers match as much as possible; lazy ones as little as possible.
'<a><b>'.match(/<.+>/)[0]; // '<a><b>' — greedy
'<a><b>'.match(/<.+?>/)[0]; // '<a>' — lazy
Anchors and boundaries
| Pattern | Meaning |
|---|---|
^ | Start of string (or line with m) |
$ | End of string (or line with m) |
\b | Word boundary |
\B | Not a word boundary |
/^\d{5}$/.test('12345'); // true — exactly five digits
/\bcat\b/.test('the cat sat'); // true
/\bcat\b/.test('concatenate'); // false
Groups
Capturing
/(\d{4})-(\d{2})/.exec('2026-10');
// ['2026-10', '2026', '10']
Non-capturing
/(?:https?):\/\//.exec('https://');
(?:...) groups without capturing, which is useful when you need grouping but not the value.
Named
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const m = re.exec('2026-10-26');
m.groups.year; // '2026'
m.groups.month; // '10'
m.groups.day; // '26'
Named groups make complex patterns readable and the extracted values self-documenting.
Backreferences
/(\w)\1/.test('aa'); // true — the same character twice
Lookahead and lookbehind
/\d+(?=px)/.exec('100px'); // ['100'] — followed by px
/\d+(?!px)/.exec('100em'); // ['100'] — not followed by px
/(?<=\$)\d+/.exec('$100'); // ['100'] — preceded by $
/(?<!\$)\d+/.exec('100'); // ['100'] — not preceded by $
Lookarounds assert a condition without consuming characters.
Common patterns
Email (pragmatic)
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
This is deliberately loose. A fully RFC-compliant email regex is enormous and still not a substitute for sending a confirmation email.
URL
/^https?:\/\/[^\s]+$/
Slug
/^[a-z0-9]+(?:-[a-z0-9]+)*$/
Hex colour
/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i
ISO date
/^\d{4}-\d{2}-\d{2}$/
Phone (digits and separators)
/^\+?[\d\s()-]{7,}$/
Trim whitespace
str.replace(/^\s+|\s+$/g, '');
// or simply
str.trim();
Escape a string for use in a regex
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
This is essential when building a regex from user input.
The lastIndex trap
The g flag makes a regex stateful.
const re = /\d/g;
re.test('1'); // true, lastIndex = 1
re.test('1'); // false, lastIndex = 2 — past the end
re.test('1'); // true, lastIndex reset to 0
The same regex object reused with test alternates between true and false. This is a real bug that appears in loops and in module-level regex constants.
The fixes:
// Create a new regex each time
/\d/g.test('1');
// Or reset lastIndex
re.lastIndex = 0;
Note that String.prototype.match with g resets lastIndex, but test and exec do not.
Performance and safety
Catastrophic backtracking
Some patterns take exponential time on certain inputs.
// Dangerous: nested quantifiers
/(a+)+$/.test('aaaaaaaaaaaaaaaaaaaaaaaaaaaaX');
The engine tries every way to partition the as, which explodes. This is a denial-of-service vector when the input is user-controlled.
Mitigations:
- Avoid nested quantifiers.
(a+)+is the classic offender. - Use atomic groups or possessive quantifiers where supported.
- Anchor the pattern so it fails fast.
- Limit the input length before matching.
- Use a linear-time engine like RE2 for untrusted input.
Compile once
// Bad: compiles on every call
function isEmail(s) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s); }
// Better: hoist the literal (engines cache literals, but be explicit)
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function isEmail(s) { return EMAIL_RE.test(s); }
When not to use regex
Parsing HTML. HTML is not a regular language. Use DOMParser or a parser library.
Parsing JSON. Use JSON.parse.
Parsing nested structures. Balanced parentheses, nested tags, and similar cannot be matched reliably.
Validating email fully. Use a loose check plus a confirmation email.
Complex date parsing. Use a date library.
Testing regexes
Regexes are easy to get subtly wrong, so testing them matters.
Use a regex tester with a visual explanation. Several online tools show the match groups and explain each part of the pattern.
Test the edge cases. An empty string, a very long string, a string with unicode, and a string that almost matches.
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Cases worth testing
EMAIL_RE.test(''); // false
EMAIL_RE.test('a@b'); // false — no dot
EMAIL_RE.test('a@b.c'); // true
EMAIL_RE.test('a b@c.d'); // false — space
EMAIL_RE.test('a@b.c.d'); // true
EMAIL_RE.test('@b.c'); // false — no local part
Test with the actual data. Real user input contains characters you did not anticipate: emoji, right-to-left marks, zero-width spaces, and combining characters.
Watch for catastrophic backtracking with a timeout in tests, so a pathological pattern fails fast rather than hanging.
Unicode
By default, regex operates on UTF-16 code units, which breaks for characters outside the Basic Multilingual Plane.
/^.$/.test('👋'); // false — the emoji is two code units
/^.$/u.test('👋'); // true — the u flag treats it as one code point
The u flag enables Unicode mode, which handles code points correctly. It also enables \p{...} property escapes.
/\p{Emoji}/u.test('👋'); // true
/\p{Letter}/u.test('é'); // true
/\p{Script=Greek}/u.test('α'); // true
Without the u flag, \p is treated as a literal p.
The v flag is a newer addition that extends u with set notation, allowing operations like intersection and subtraction within character classes.
/[\p{Letter}--[a-z]]/v.test('é'); // true — a letter that is not a-z
Practical guidance
- Use
testfor boolean checks andmatchfor the values. - Use named capture groups for readability.
- Escape user input before building a regex.
- Watch the
lastIndextrap with thegflag. - Avoid nested quantifiers on untrusted input.
- Anchor patterns with
^and$when matching a whole string. - Use
\bfor word boundaries. - Do not parse HTML with regex.
For the related guides, see javascript-date-handling and javascript-array-methods-guide. For the broader context, form-validation-patterns and javascript-optional-chaining.
Quotable summary
A regular expression is a pattern for matching text, written between slashes with optional flags after the closing slash. The g flag makes a regex stateful via lastIndex, which causes bugs when the same regex object is reused with test, since it alternates between true and false. Use test for a boolean check, match for the matches, and replace for substitution, and use named capture groups to make complex patterns readable. Regex is the wrong tool for parsing nested structures like HTML, which is not a regular language, and nested quantifiers like (a+)+ can cause catastrophic backtracking, which is a denial-of-service vector on untrusted input. Always escape user input before building a regex from it.