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.
Tools mentioned in this post
Related reading
Why your JSON won't parse (and how to fix it in 30 seconds)
Trailing commas, unquoted keys, single quotes, comments - the five errors that break 90% of hand-written JSON, and how to catch them without a build step.
Cron expressions explained (for people who forget them every time)
The five fields, the special characters, and the schedules everyone actually uses. A field guide for anyone who Googles 'cron every 5 minutes' more than once a month.
JWT explained: what actually goes inside that token
Every login flow you touch these days involves JWTs, but 'JSON Web Token' hides a lot. Here's the three-part structure, the security pitfalls, and when not to use them.
The best free physics editor alternatives for 2D game devs in 2026
Every 2D game needs collision shapes, and every paid physics editor charges you for them. Here's what a physics body editor actually does, what to look for in a free one, and how the current free options - desktop and browser - stack up in 2026.
Shan builds 712 Tools. He holds a Master's degree in Mechanical Engineering and now works as a Software Engineer, shipping browser-based developer utilities out of Ontario, Canada. Learn more ยท 712studiogames@gmail.com