Regular expressions (regex) are one of the most powerful tools in a JavaScript developer's toolkit. Whether you're validating user input, parsing text, or extracting data from strings, mastering regex will dramatically improve your productivity. This complete tutorial covers everything from basics to advanced features — with practical examples you can use immediately.
Introduction to Regex in JavaScript
Regular expressions, commonly called regex or regexp, are sequences of characters that define search patterns used for matching, extracting, and manipulating text. In JavaScript, regular expressions are first-class objects built into the language, supported by dedicated syntax and a rich set of string and regex methods.
JavaScript supports regular expressions through the RegExp object and through regex literals enclosed in forward slashes. A regex literal like /hello/i creates a pattern that matches the word hello case-insensitively. The RegExp constructor, written as new RegExp('hello', 'i'), achieves the same result but allows dynamic pattern construction from variables and user input.
Regex is an essential skill for JavaScript developers because text processing is central to web development. Form validation, URL routing, template parsing, syntax highlighting, and data extraction all rely on pattern matching.
Creating Regex Patterns
The simplest regex pattern is a literal string match. The pattern /cat/ matches the exact sequence of characters c, a, t anywhere in a string. By default, regex is case-sensitive. Adding the i flag makes the match case-insensitive.
Special characters called metacharacters give regex its power beyond simple literal matching:
-
.— matches any single character except a newline -
^— anchors a pattern to the start of the string -
$— anchors a pattern to the end -
()— creates capturing groups -
|— alternation operator (logical OR) -
[]— defines character classes
When you need to match a metacharacter literally, escape it with a backslash. To match an actual dot, use \..
Common flags:
-
g— global (find all matches) -
i— case-insensitive -
m— multiline -
s— dotAll (dot matches newlines) -
u— Unicode mode -
d— indices for capture groups
Character Classes and Quantifiers
Character classes define sets of characters that can match at a specific position. [aeiou] matches any single vowel. [^aeiou] negates the class. Ranges: [a-z], [0-9], [a-zA-Z0-9].
Shorthand character classes:
-
\d— any digit (0-9) -
\D— non-digit -
\w— word character (letters, digits, underscore) -
\W— non-word character -
\s— whitespace -
\S— non-whitespace
Quantifiers:
-
?— zero or one -
*— zero or more -
+— one or more -
{3}— exactly three -
{2,5}— between two and five -
{3,}— three or more
By default, quantifiers are greedy (match as much as possible). Adding ? makes them lazy (match as little as possible).
Common Regex Methods in JavaScript
JavaScript provides regex functionality through both RegExp methods and String methods.
test() — Returns true/false:
const pattern = /hello/i;
pattern.test("Hello World"); // true
match() — Returns match details:
const str = "The year is 2026";
const result = str.match(/\d+/);
console.log(result[0]); // "2026"
matchAll() — Returns all matches as iterator:
const str = "cat and bat and rat";
const matches = [...str.matchAll(/\w+at/g)];
// [["cat"], ["bat"], ["rat"]]
replace() / replaceAll() — Substitute matches:
"hello world".replace(/world/, "JavaScript");
// "hello JavaScript"
split() — Divide string using regex as delimiter:
"one, two three;four".split(/[,;\s]+/);
// ["one", "two", "three", "four"]
Practical Regex Examples
Email validation:
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
emailRegex.test("user@example.com"); // true
Phone number (flexible format):
const phoneRegex = /^\+?[\d\s()-]{10,}$/;
phoneRegex.test("+1 (555) 123-4567"); // true
URL validation:
const urlRegex = /^https?:\/\/[\w.-]+\.[a-z]{2,}(\/\S*)?$/i;
urlRegex.test("https://dev.to"); // true
Password strength (8+ chars, uppercase, lowercase, digit, special):
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;
passwordRegex.test("Strong@123"); // true
Advanced Regex Features
Lookahead and Lookbehind:
// Positive lookahead: number followed by USD
/\d+(?=\sUSD)/.exec("100 USD")[0]; // "100"
// Negative lookbehind: word not preceded by "not"
/(?<!not\s)\bgood\b/.test("this is good"); // true
Named Capture Groups:
const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = "2026-04-10".match(dateRegex);
console.log(match.groups.year); // "2026"
Non-Capturing Groups:
// Group without capturing
/(?:https?:\/\/)?([\w.-]+)/.exec("https://example.com")[1];
// "example.com"
Unicode Property Escapes:
// Match any letter from any language
/\p{L}+/u.test("café"); // true
/\p{L}+/u.test("日本語"); // true
Testing Your Regex Online
Online regex testing tools are indispensable for developing and debugging regular expressions. These tools let you enter a pattern and test string, then instantly see all matches highlighted in the text. The immediate visual feedback makes it dramatically easier to iterate on a pattern compared to writing code, running it, and inspecting the output.
When developing complex regex patterns, build them incrementally. Start with the simplest possible pattern that matches the core of what you need, then add components one at a time. After each addition, verify that existing matches are preserved and new edge cases are handled.
Performance matters too. Some patterns, particularly those with nested quantifiers or overlapping alternatives, can exhibit catastrophic backtracking where the regex engine explores an exponential number of paths. If a pattern takes thousands of steps to match a short string, it needs restructuring.
Try It Yourself 🚀
I built a free JavaScript Regex Tester with live highlighting, capture group inspection, and flag toggles — no signup needed:
It's 100% client-side, so your regex and test strings never leave your browser.
Conclusion
Regular expressions are a skill that pays dividends for your entire programming career. Start with the basics — literal matches, character classes, quantifiers — and build up to advanced features like lookaheads and named groups as you need them. The key is consistent practice and testing your patterns against real-world input.
What's your favorite regex pattern? Drop it in the comments below! 💬
Top comments (0)