Knowing how to use regex in JavaScript is one of those skills that separates productive developers from frustrated ones. Whether you're validating form inputs, parsing log files, or transforming strings at scale, regular expressions let you express complex text-matching logic in a single, compact line. This guide walks through everything from the basics of the RegExp object to advanced features like named capture groups and lookahead assertions — with real examples you can drop straight into your projects.
The RegExp Object: Two Ways to Create a Regex
JavaScript gives you two syntaxes for constructing a regular expression:
// Literal syntax — preferred for static patterns
const pattern = /hello/i;
// Constructor syntax — use when the pattern is dynamic
const userInput = 'world';
const dynamic = new RegExp(userInput, 'i');
The literal syntax is evaluated at parse time and is slightly faster. Use the constructor when you need to build the pattern from a variable or user input. Just remember to escape any special regex characters in that string first.
The Core Methods: test, match, replace, and split
RegExp.prototype.test()
test() returns a boolean — perfect for validation gates:
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailPattern.test('user@example.com')); // true
console.log(emailPattern.test('not-an-email')); // false
String.prototype.match()
match() returns an array of results. Without the g flag it returns the first match plus capture groups; with g it returns all matches:
const sentence = 'The price is $14.99 and $3.50';
const prices = sentence.match(/\$[\d.]+/g);
console.log(prices); // ['$14.99', '$3.50']
String.prototype.replace()
replace() accepts a regex as its first argument. Use $1, $2 etc. to reference capture groups in the replacement string:
const date = '2026-03-21';
const formatted = date.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1');
console.log(formatted); // '21/03/2026'
String.prototype.split()
Split on any whitespace run, not just single spaces:
const messy = 'one two\tthree\nfour';
const words = messy.split(/\s+/);
console.log(words); // ['one', 'two', 'three', 'four']
Understanding Flags
Flags modify how a regex engine processes text. The most important ones are:
- g (global) — find all matches, not just the first
- i (case-insensitive) — match uppercase and lowercase interchangeably
-
m (multiline) — make
^and$match the start/end of each line, not just the whole string -
s (dotAll) — make
.match newline characters too - u (unicode) — enable full Unicode mode, required for emoji or astral-plane characters
-
d (indices) — populate a
indicesproperty on match results with start/end positions (ES2022)
// Multiline: match lines starting with a hash
const markdown = `# Title\nsome text\n# Another`;
const headings = markdown.match(/^#.+/gm);
console.log(headings); // ['# Title', '# Another']
Named Capture Groups
Instead of referencing captures as $1 or match[1], you can name them with (?<name>...). This makes regex far easier to maintain:
const iso = '2026-03-21T14:30:00Z';
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { groups } = iso.match(re);
console.log(groups.year); // '2026'
console.log(groups.month); // '03'
console.log(groups.day); // '21'
Named groups also work in replace() via $<name>:
const reordered = '2026-03-21'.replace(
/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
'$<d>/$<m>/$<y>'
);
console.log(reordered); // '21/03/2026'
Lookahead and Lookbehind Assertions
Lookarounds let you match text only when it is (or isn't) preceded or followed by something else, without consuming those surrounding characters.
-
Positive lookahead
(?=...)— match if followed by pattern -
Negative lookahead
(?!...)— match if NOT followed by pattern -
Positive lookbehind
(?<=...)— match if preceded by pattern -
Negative lookbehind
(?<!...)— match if NOT preceded by pattern
// Extract numbers that are preceded by a dollar sign
const text = 'USD: $199.99, EUR: €89';
const usdAmounts = text.match(/(?<=\$)[\d.]+/g);
console.log(usdAmounts); // ['199.99']
// Match passwords that contain at least one digit
const strong = /^(?=.*\d).{8,}$/;
console.log(strong.test('myPass9!')); // true
console.log(strong.test('mypassword')); // false
Common Real-World Patterns
Email Validation
const email = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
URL Matching
const url = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)/;
Phone Numbers (US Format)
const phone = /^(\+1[\s-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
console.log(phone.test('(555) 867-5309')); // true
console.log(phone.test('+1 555-867-5309')); // true
Slug Sanitization
function toSlug(str) {
return str
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-');
}
console.log(toSlug('Hello, World! 2026')); // 'hello-world-2026'
Performance Tips
Regex can be a bottleneck if used carelessly. A few guidelines:
- Compile patterns once outside loops —
const re = /pattern/;— rather than recreating inside each iteration. - Be specific:
/\d{4}/is faster and clearer than/.{4}/when you know you want digits. - Avoid catastrophic backtracking by anchoring patterns and avoiding nested quantifiers like
(a+)+. - Use
String.includes()orString.startsWith()for plain substring checks — they're faster than regex when no pattern is needed.
Test Your Patterns Interactively
Writing regex blind is painful. Use the DevPlaybook Regex Tester to visualize matches, tweak flags, and inspect capture groups in real time before committing to code. You can also pair it with the guide on our Regex Cheat Sheet for a quick reference on syntax tokens.
Want these tools available offline? The DevToolkit Bundle ($9 on Gumroad) packages 40+ developer tools into a single downloadable kit — no internet required.
Conclusion
Regular expressions in JavaScript are a superpower once you understand the building blocks. Start with test() and match() for simple use cases, reach for named capture groups when readability matters, and leverage lookaheads when you need context-aware matching without consuming characters. Keep your patterns compiled outside loops, and always validate against edge cases — regex is only as reliable as the test suite behind it.
Free Developer Tools
If you found this article helpful, check out DevToolkit — 40+ free browser-based developer tools with no signup required.
Popular tools: JSON Formatter · Regex Tester · JWT Decoder · Base64 Encoder
🛒 Get the DevToolkit Starter Kit on Gumroad — source code, deployment guide, and customization templates.
Top comments (0)