The regex cheat sheet every JavaScript developer actually needs
Forget lookbehind edge cases. Here are the 15 patterns you'll use in real code — validation, extraction, replacement — with the JavaScript-specific gotchas.
Why yet another regex guide
Because most regex references cover PCRE, Python, or Ruby — and JavaScript's regex engine has enough quirks that examples copied from Stack Overflow often silently misbehave. This guide is JavaScript-only.
The 15 patterns you'll actually use
1. Email (good enough): /^[^\s@]+@[^\s@]+\.[^\s@]+$/ — matches anything that looks vaguely email-shaped. Don't try to match the full RFC 5322 spec; use a real validator for anything critical.
2. URL: /^https?:\/\/[^\s]+$/ — same principle. For real validation use new URL(str) in a try/catch.
3. UUID v4: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
4. ISO date (YYYY-MM-DD): /^\d{4}-\d{2}-\d{2}$/ — shape check only. Use Date.parse for validity.
5. Hex color: /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i
6. Semver: /^\d+\.\d+\.\d+(?:-[\w.]+)?(?:\+[\w.]+)?$/
7. Trim whitespace: str.replace(/^\s+|\s+$/g, '') — or just use str.trim(), which is faster.
8. Collapse multiple spaces: str.replace(/\s+/g, ' ')
9. Extract numbers from a string: str.match(/-?\d+(?:\.\d+)?/g)
10. Split camelCase: str.replace(/([a-z])([A-Z])/g, '$1 $2')
11. Escape regex special chars: str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
12. Match a whole word: new RegExp(\b${word}\b) — after escaping.
13. Non-greedy match: /<.*?>/ — the ? after a quantifier is essential for HTML/log parsing.
14. Named groups: /(?<year>\d{4})-(?<month>\d{2})/ — access as match.groups.year.
15. Multiline mode: flag m makes ^ and $ match line breaks, not just string boundaries.
JavaScript-specific gotchas
\d does not include Unicode digits by default. /\d/ matches only 0-9. To match Devanagari digits, Arabic digits, etc., add the u flag and use \p{Nd} instead.
Lookbehind is supported (finally) but slow. (?<=foo)bar works in modern engines. On very large strings the performance hit is real — prefer capture groups for hot paths.
The g flag makes match() return an array of strings, not match objects. For match objects with groups, use matchAll() instead.
Regex literals are cached; RegExp constructor is not. while(true) { /foo/.test(str) } reuses the same object. while(true) { new RegExp('foo').test(str) } allocates every iteration.
The dotAll flag s makes . match newlines. Without it, . skips \n. Essential for multi-line parsing.
The catastrophic backtracking trap
The single biggest way to melt your Node process:
const bad = /(a+)+$/;
bad.test('a'.repeat(30) + '!'); // hangs for seconds
Nested quantifiers on the same character class create exponential backtracking. The fix is usually a possessive quantifier — but JavaScript regex doesn't support those. Workarounds:
- Unroll the loop:
/^a+$/instead of/(a+)+$/. - Anchor tightly:
^and$prune search space. - Use lookahead trickery:
/(?=(a+))\1$/mimics atomic groups. - Just don't — for anything user-supplied, prefer a real parser over a clever regex.
Regex Tester shows a warning when a match takes more than a few hundred milliseconds — a good early signal that your pattern is going to bite you in production.
When regex is the wrong tool
Three cases:
- HTML. The famous "you can't parse HTML with regex" answer on Stack Overflow is right for arbitrary HTML. For a controlled subset (extracting all
hrefvalues from your own emails) it's fine. - JSON. Use
JSON.parse. Regex will bite you on nested objects and escaped quotes. - Nested structures generally. Matching balanced parentheses is provably impossible in a regular expression. Use a stack-based parser.
Testing without a REPL
Building a regex is a debug cycle: pattern → sample input → check matches → adjust. Regex Tester does this loop live in the browser — matches highlight as you type, capture groups show in the sidebar, and there's no risk of pasting production data into a third-party server.
Related tools:
- JSON Formatter — after you've extracted the interesting substring.
- URL Encoder — for patterns that need to survive query strings.