Regular expressions power search, validation, and text cleanup across JavaScript apps. This hub links to 44 RegExp tutorials — from exec() and test() through character classes, quantifiers, anchors, and flags.
01
/pattern/
Literals
02
test()
Yes / no
03
exec()
Captures
04
\d + *
Patterns
05
g i m
Flags
06
44 guides
Full index
Fundamentals
Introduction
A regular expression (regex) is a compact language for describing text patterns. In JavaScript, patterns live in RegExp objects. You use them to validate emails, extract numbers, strip HTML tags, or find every word in a paragraph.
What Are Regular Expressions?
Regex combines literal characters (match exactly) with special tokens like \d (digit), + (one or more), and [a-z] (character range). The engine scans a string left to right and reports whether — and where — the pattern matched.
💡
Beginner Tip
Start with simple literal patterns like /cat/, then add anchors (^, $) for whole-field validation. Complex patterns are built from small, testable pieces.
Two Ways to Create a RegExp
Literal — /pattern/flags when the pattern is fixed in source code.
Constructor — new RegExp("pattern", "flags") when the pattern comes from user input or variables.
String methods — str.match(), str.replace(), and str.search() accept regex too.
Pattern Building Blocks
Character classes — [0-9], [a-z], [^abc] (negated).
Metacharacters — \d, \w, \s, . (wildcard).
Quantifiers — ?, +, *, {2,5} control repetition.
Groups — (abc) capture parts; (a|b) alternation.
Flags — g global, i ignore case, m multiline.
Foundation
📝 Syntax
Create a regex and test a string:
JavaScript
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const ok = email.test("ada@example.com");
const digits = /\d+/g;
const found = "Order 42 and 7".match(digits); // ["42", "7"]
Common RegExp methods
Method
Returns
Best for
regex.test(str)
true / false
Validation, guards
regex.exec(str)
Match array or null
Capture groups, loops with g
str.match(regex)
Matches array or null
Quick extraction
str.replace(regex, repl)
New string
Cleanup and substitution
Cheat Sheet
⚡ Quick Reference
Goal
Pattern / API
Any digit
\d or [0-9]
Word characters
\w (letters, digits, _)
Start of string
^
End of string
$
One or more
+
Optional
?
Exact count
{4} (e.g. PIN length)
Case insensitive
/pattern/i
Context
When to Use Regular Expressions
Form validation — emails, phone numbers, postal codes (combine with anchors).
^ and $ anchor the pattern to the whole string. \d+ means one or more digits. test() returns a simple boolean — ideal for validation.
📈 Extract & Replace
Pull data out of text and transform it.
Example 3 — Capture Groups with exec()
Extract the username and domain from an email-like string.
JavaScript
const line = "Contact: ada@example.com today";
const email = /(\w+)@([\w.]+)/;
const m = email.exec(line);
console.log(m[0]); // full match
console.log(m[1]); // ada
console.log(m[2]); // example.com
Parentheses create capture groups. Index 0 is the full match; 1 and 2 hold grouped parts. Use exec() when you need structured data, not just true/false.
^ and $ require the entire input to match. [^\s@]+ means “one or more characters that are not whitespace or @.” Real apps may still verify via a confirmation email.
Tips
💬 Usage Tips
Anchor whole fields — use ^ and $ in validation so abc123 does not pass a digits-only rule.
Prefer literals for fixed patterns — /\d+/ is clearer than new RegExp("\\d+").
Escape user input — when building new RegExp from variables, escape metacharacters first.
Reset lastIndex — global regexes remember position; set regex.lastIndex = 0 before reusing.
Search this index — jump to any of 44 tutorials above.
Watch Out
⚠️ Common Pitfalls
Greedy quantifiers — .* may swallow too much; use non-greedy .*? when needed.
Missing anchors — /\d+/ matches a substring; /^\d+$/ validates the whole value.
Global flag side effects — test() and exec() advance lastIndex on /g regexes.
Overly complex patterns — split into named steps or use a parser for nested data (JSON, HTML).
Octal escapes — \123 can be ambiguous; prefer \xHH or \uXXXX.
🧠 How RegExp Matching Works
1
Compile pattern
JavaScript turns /pattern/flags into an internal RegExp object.
Parse
2
Scan input
The engine walks the string, trying the pattern at each position (unless anchored).
Search
3
Return result
test() yields boolean; exec() yields match data or null.
Report
=
🔍
Text superpowers
Validation, extraction, and cleanup become declarative one-liners instead of manual loops.
Compatibility
🖥 Browser & Node Support
RegExp and core methods (test, exec, string match/replace) are supported in every modern browser and all Node.js versions. Newer flags like d (indices) and u (Unicode) require recent engines — check MDN for your target.
✓ Baseline · ES3+
RegExp.prototype methods
Production-safe across all current runtimes. Pattern syntax follows ECMAScript rules; test in your environment when using newer flags.
100%Core API
Wrap Up
🎉 Conclusion
Regular expressions turn messy string work into focused patterns. Start with test() and exec(), learn \d and quantifiers, then explore flags and anchors as your validation needs grow.
Use the searchable index to open all 44 tutorials — each includes try-it labs and FAQs.
A RegExp is a pattern that describes text to find in strings. You create one with a literal like /hello/i or new RegExp('hello', 'i'), then use methods like test(), exec(), or String methods match, replace, and search.
Use test() when you only need true or false — form validation, guards, filters. Use exec() when you need the matched text, capture groups, or the index where the match started.
g (global) finds all matches instead of stopping at the first. i (ignoreCase) makes letters match regardless of case. m (multiline) makes ^ and $ match the start and end of each line, not just the whole string.
They match the same thing — any digit. \d is shorthand and easier to read. [0-9] is explicit and useful when you need custom ranges like [2-9].
By default, . matches any character except line terminators. Use the s (dotAll) flag in modern engines, or [\s\S] as a workaround, when you need . to span multiple lines.
Read the overview, try the five examples, then open exec() or test() under Instance Methods. Use the search box to jump to any of the 43 pattern and method tutorials.
Did you know?
JavaScript regex literals cannot be empty — // starts a line comment. To match a forward slash in a literal, escape it: /\//. With new RegExp, pass "\\/" instead.