Skip to content
Velloreth
Programming 8 min read

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

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

FlagMeaning
gGlobal — find all matches
iCase-insensitive
mMultiline — ^ and $ match line boundaries
sDotall — . matches newlines
uUnicode — proper code point handling
ySticky — match only at lastIndex
dIndices — 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']

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

PatternMatches
.Any character except newline
\dDigit
\DNot a digit
\wWord character (letter, digit, underscore)
\WNot a word character
\sWhitespace
\SNot whitespace
[abc]Any of a, b, c
[^abc]Not a, b, or c
[a-z]Range
[a-zA-Z0-9]Multiple ranges

Quantifiers

PatternMeaning
*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

PatternMeaning
^Start of string (or line with m)
$End of string (or line with m)
\bWord boundary
\BNot 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 test for boolean checks and match for the values.
  • Use named capture groups for readability.
  • Escape user input before building a regex.
  • Watch the lastIndex trap with the g flag.
  • Avoid nested quantifiers on untrusted input.
  • Anchor patterns with ^ and $ when matching a whole string.
  • Use \b for 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.

Frequently asked questions

What does the g flag do?
It makes the regex global, so it finds all matches rather than stopping at the first. It also makes the regex stateful: lastIndex advances between calls, which causes surprising results when the same object is reused with test.
What is the difference between test and match?
test returns a boolean and is the fastest way to check for a match. match returns the matched text and capture groups, or null. Use test when you only need to know whether it matched.
What are named capture groups?
They let you name a group with (?<name>...) and read it from the result's groups property, instead of relying on positional indices. This makes complex patterns much more readable.
How do I escape special characters?
Prefix them with a backslash. The special characters are . * + ? ^ $ { } ( ) | [ ] \. To escape a whole string, use a helper that replaces each special character with a backslash-prefixed version.
Why does my regex work once and then fail?
Because the g flag makes the regex stateful. lastIndex advances after each match, so the next test starts from the wrong position. Create a new regex per use, or reset lastIndex to 0.
Should I use regex to parse HTML?
No. HTML is not a regular language, and regex cannot handle nesting reliably. Use the DOMParser in the browser or a parser library in Node.