Regular expressions (regex) are one of the highest-leverage skills in software engineering. A single well-crafted expression can validate an invoice ID, extract structured timestamps from a 10,000-line server log, or sanitize user-entered slugs before saving them to a database. At the same time, poorly understood regex syntax leads to subtle edge-case bugs, accidental partial matches, and even denial-of-service freezes caused by catastrophic backtracking.
This guide serves as both a complete reference cheat sheet and a practical handbook for writing fast, readable, bug-free JavaScript regular expressions. You can test every pattern below live with capture-group highlighting inside our Online Regex Tester.
- 1. Core Regex Building Blocks & Character Classes
- 2. Anchors & Word Boundaries (Why Validation Fails Without
^and$) - 3. Greedy vs. Lazy Quantifiers Explained
- 4. Capturing Groups, Named Groups & Non-Capturing Groups
- 5. Positive & Negative Lookaheads / Lookbehinds
- 6. JavaScript Flags (
g,i,m,s,u) & thelastIndexTrap - 7. Avoiding Catastrophic Backtracking (ReDoS)
- 8. Battle-Tested Production Patterns
- 9. When NOT to Use Regex (HTML, JSON & URLs)
1. Core Regex Building Blocks & Character Classes
Every regular expression combines literal characters with special metacharacters that describe character sets, positions, and repetition counts:
| Token | Meaning | Example & Match |
|---|---|---|
. | Any single character except newline (unless s flag is on) | a.c matches abc, a-c |
\d / \D | Any digit [0-9] / any non-digit | \d{4} matches 2026 |
\w / \W | Word char [A-Za-z0-9_] / non-word char | \w+ matches user_42 |
\s / \S | Whitespace (space, tab, newline) / non-whitespace | a\s+b matches a b |
[abc] / [^abc] | Any listed character / any character NOT listed | [^"]+ matches until next quote |
a|b | Alternation (logical OR) | (?:jpg|png|webp) |
Remember escaping: Characters like ., +, *, ?, ^, $, (, ), [, and \ carry special meaning. To match a literal dot in a domain name or price, escape it with a backslash: \..
2. Anchors & Word Boundaries (Why Validation Fails Without ^ and $)
The #1 validation bug in web apps occurs when developers forget start and end anchors. Testing /\d{6}/.test("PIN: 123456abc") returns true because the engine merely checks whether six digits appear anywhere inside the string!
^asserts the start of the string (or start of each line when the multilinemflag is enabled).$asserts the end of the string (or end of each line withm).\basserts a word boundary—the zero-width position between a\wcharacter and a non-word character (or string edge). Great for extracting standalone words or IP addresses inside log lines without accidentally matching partial numbers.
// Unsafe validation: matches "hello999999world"
const loosePin = /\d{6}/;
// Safe full-string validation: matches ONLY exact 6-digit PINs
const strictPin = /^\d{6}$/;
3. Greedy vs. Lazy Quantifiers Explained
Quantifiers control how many times the preceding token may repeat: * (0 or more), + (1 or more), ? (0 or 1), and {m,n} (between m and n times).
By default, quantifiers are greedy—they grab as many characters as possible while still letting the rest of the pattern match. Consider extracting quoted strings from "alpha" and "beta":
- Greedy
".*": Starts at the first quote and consumes all the way to the final quote, returning one giant match:"alpha" and "beta"! - Lazy
".*?": Adding?after a quantifier makes it reluctant, stopping at the earliest closing quote to return two separate matches:"alpha"and"beta". - Even Faster Negated Class
"[^"]*": Explicitly matching non-quote characters avoids backtracking altogether and runs significantly faster on large inputs.
4. Capturing Groups, Named Groups & Non-Capturing Groups
Parentheses serve two purposes: grouping tokens together (for quantifiers or alternation) and extracting matched substrings:
- Standard Capturing Group
(...): Stores the matched text in sequential slots (match[1],match[2], or$1,$2inString.replace()). - Named Capturing Group
(?<year>\d{4}): Available in modern ES2018+ JavaScript, named groups let you readmatch.groups.yearinstead of brittle numeric indices. - Non-Capturing Group
(?:...): Groups alternation like(?:http|https):\/\/without wasting memory or shifting capture group numbering.
const logLine = "2026-12-01 ERROR status=502 path=/api/orders";
const rx = /^(?<date>\d{4}-\d{2}-\d{2})\s+(?<level>\w+)\s+status=(?<status>\d{3})\s+path=(?<path>\S+)/;
const match = logLine.match(rx);
console.log(match.groups);
// { date: "2026-12-01", level: "ERROR", status: "502", path: "/api/orders" }
5. Positive & Negative Lookaheads / Lookbehinds
Lookarounds check what comes immediately ahead of or behind the current cursor without consuming any characters in the final match:
- Positive Lookahead
(?=...): Match only if followed by pattern. Example:\d+(?=px)extracts24from"24px"without includingpx. - Negative Lookahead
(?!...): Match only if not followed by pattern. Example:\d+(?!px)skips pixel measurements. - Password Complexity Checks: Multiple lookaheads anchored at
^verify independent rules simultaneously in any order:^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$enforces lowercase, uppercase, digit, and minimum 8-character length cleanly. - Lookbehind
(?<=...)/(?<!...): Supported in ES2018+ (Chrome, Firefox, Safari 16.4+, Node.js), e.g.,(?<=\$)\d+extracts numbers preceded by a dollar sign.
6. JavaScript Flags & the Infamous /g lastIndex Trap
Flags placed after the closing slash alter engine behavior: g (global—find all matches), i (case-insensitive), m (multiline ^/$), s (dotAll—. matches newlines), and u (full Unicode mode for emojis and surrogate pairs).
Critical JavaScript Gotcha: A RegExp literal with the g flag is stateful! Every call to rx.test(str) advances rx.lastIndex to the end of the previous match. Calling it twice on identical valid strings alternates between true and false:
const badRx = /^[a-z]+$/g;
console.log(badRx.test("hello")); // true (lastIndex becomes 5)
console.log(badRx.test("hello")); // false! (starts searching at index 5)
// Fix: NEVER put the "g" flag on a boolean validation regex
const goodRx = /^[a-z]+$/;
7. Avoiding Catastrophic Backtracking (ReDoS)
JavaScript uses a backtracking NFA regex engine. When you nest variable quantifiers over overlapping patterns—like ^(a+)+$ or ^([a-zA-Z0-9]+)*@$—a slightly invalid string at the end forces the engine to explore an exponential 2^n number of paths before failing. Just 30 characters of bad input can freeze a browser tab or Node.js event loop for minutes—a vulnerability known as ReDoS (Regular Expression Denial of Service).
Three rules to eliminate ReDoS risk:
- Never place
+or*directly inside another group that also has+or*. - Ensure alternatives inside
(A|B)+are mutually exclusive so an input character cannot match both branches. - Limit untrusted user input string lengths before running complex regexes, or test patterns against non-matching strings inside our Regex Tester.
8. Battle-Tested Production Patterns
// 1. Practical Email Format (strict full check should still send a confirmation email)
^[^\s@]+@[^\s@]+\.[^\s@]{2,}$
// 2. ISO-8601 Date (YYYY-MM-DD)
^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
// 3. IPv4 Address (0.0.0.0 to 255.255.255.255)
^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$
// 4. URL-Safe SEO Slug (lowercase alphanumeric segments separated by single hyphens)
^[a-z0-9]+(?:-[a-z0-9]+)*$
// 5. Hex Color (#RGB or #RRGGBB)
^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
// 6. Semantic Version (SemVer 2.0)
^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$
9. When NOT to Use Regex (HTML, JSON & URLs)
Regex excels at flat token patterns, not recursive nested grammars. Avoid writing regexes to parse arbitrary JSON objects, nested HTML tags, or full query strings—nested structures quickly break regular expressions. Instead, use JSON.parse() (and debug syntax with our JSON Validator), the browser's DOMParser for HTML, and the native URL / URLSearchParams APIs (see our URL Query Parser).
10. Real-World Search & Replace Recipes in JavaScript
Beyond boolean validation, regular expressions shine when cleaning messy datasets, masking sensitive fields in logs before troubleshooting, or normalizing user input:
// 1. Mask credit card digits / API keys before writing logs
const rawLog = "user=42 api_key=sk_live_9876543210abcdef email=dev@techcar.online";
const maskedLog = rawLog.replace(/\bsk_live_[A-Za-z0-9]{8,}\b/g, "sk_live_***REDACTED***");
// 2. Convert camelCase identifiers to kebab-case URL slugs
function toKebabCase(str) {
return str
.replace(/([a-z0-9])([A-Z])/g, "$1-$2")
.toLowerCase();
}
console.log(toKebabCase("jsonFormatterTool")); // "json-formatter-tool"
// 3. Collapse extra whitespace and trim lines safely
const messyText = " hello world \n\n from regex ";
const cleanText = messyText.replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
// 4. Safely extract all hashtags without matching CSS hex colors like #fff
const post = "Learning #JavaScript and #Regex! Color #2563eb stays ignored.";
const tags = [...post.matchAll(/(?:^|\s)(#[A-Za-z][A-Za-z0-9_]*)/g)].map((m) => m[1]);
11. Unicode Property Escapes for Multilingual Apps
Legacy patterns like [a-zA-Z] silently reject valid names containing accented letters (like José or Müller) or Hindi/Devanagari characters. In modern JavaScript (ES2018+), adding the u (Unicode) flag unlocks Unicode property escapes such as \p{L} (any letter in any language) and \p{N} (any numeric digit):
// Matches letters across English, Hindi, Spanish, French, Japanese, etc.
const unicodeWord = /^[\p{L}\p{N}_-]+$/u;
console.log(unicodeWord.test("Gajendra")); // true
console.log(unicodeWord.test("नमस्ते")); // true
console.log(unicodeWord.test("José_42")); // true
Always test multilingual patterns against real edge cases inside our Online Regex Tester with the u flag enabled so international users never hit unexpected form errors.
12. Regex Performance Tips for Large Inputs & Loops
When processing thousands of log lines, CSV rows, or API records in a tight loop, small regex habits make a measurable difference in CPU time and memory allocation:
- Compile the
RegExponce outside the loop: Creatingnew RegExp(pattern)inside aforloop over 50,000 rows recompiles the finite automaton 50,000 times. Declare constant patterns once at module scope. - Prefer simple string methods when no pattern is needed: Checking if a URL starts with
"https://"is noticeably faster withurl.startsWith("https://")orstr.includes("error")than invoking a regex engine. - Anchor patterns early with
^: When validating whole strings, starting with^tells the engine to fail immediately on index 0 if the first character doesn't match, instead of scanning forward through the entire string trying every starting offset. - Use non-capturing groups
(?:...)when you don't need captures: Skipping unnecessary array allocations for unused capture slots keeps garbage collection quiet during bulk text parsing.
13. Subtle Differences Across JavaScript, Python & PCRE
If you copy a regex from Stack Overflow or a Python backend script into frontend JavaScript, watch out for three subtle engine differences:
- Named capture group syntax: JavaScript uses
(?<name>...), whereas Python uses(?P<name>...). - Verbose comments mode (
/x): Python (re.VERBOSE) and PCRE allow multi-line whitespace and# commentsinside regexes; JavaScript has no/xflag, so avoid pasting commented multi-line PCRE patterns directly into JS literals. ^and$vs.\Aand\Z: Python and Ruby support\A(absolute start of string) and\Z(absolute end). JavaScript does not support\A/\Z—omit themflag when you want^and$to match only the start and end of the entire string.
Frequently Asked Questions
Why does String.prototype.matchAll() throw an error without the g flag?
JavaScript requires matchAll(rx) to receive a regex with the global g flag so it knows to iterate across all matches rather than stopping at the first result.
How do I match an arbitrary user search string safely inside new RegExp()?
Escape special regex characters first: str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") (or use RegExp.escape() where supported) so characters like + or ( do not throw a SyntaxError.
What is the difference between \d and [0-9]?
In JavaScript without Unicode property escapes, both match ASCII digits 0–9. Writing [0-9] explicitly makes intent unmistakable across different languages like Python, where \d also matches Unicode Arabic-Indic digits unless re.ASCII is set.
Should I validate email addresses purely with a 500-character RFC 5322 regex?
No. Overly complex email regexes often reject valid addresses with uncommon TLDs or cause ReDoS slowdowns. Use a simple sanity regex (^[^\s@]+@[^\s@]+\.[^\s@]+$) and verify real deliverability by sending a confirmation link.