Regular Expressions
Master the art of pattern matching. Use Regular Expressions to validate emails, extract phone numbers, and manipulate text with extreme precision.
Pattern Matching
A **Regular Expression** (Regex) is a sequence of characters that forms a search pattern. Instead of searching for an exact word like 'apple', you can search for a pattern like 'any three digits followed by a hyphen'.
In JavaScript, you create them by wrapping the pattern in forward slashes: /pattern/flags.
Validation and Extraction
Regex is the undisputed king of text processing. Why write 20 lines of if/else statements to check if an email is valid when a single regex can validate the format instantly?
It is primarily used for **Validation** (e.g., regex.test(password) returning true or false) and **Extraction** (e.g., text.match(regex) returning an array of all phone numbers found in a giant document).
The Syntax Toolkit
Regex looks like gibberish until you learn the basic toolkit:
- \d matches any digit (0-9). \w matches any word character (a-z, A-Z, 0-9, _).
- + means 'one or more'. * means 'zero or more'. ? means 'optional'.
- {3} means 'exactly three times'.
- ^ means start of string. $ means end of string.
So, /^\d{3}-\d{4}$/ perfectly matches a 7-digit phone number format like '555-1234'.
The Live Matcher
Type a regex pattern below and toggle the 'global' flag. Watch how the matching substrings in the sample text instantly highlight as your pattern takes shape.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Regular Expressions are patterns used to match character combinations in strings.
- Define them using literal syntax
/pattern/flags. - Use character classes like
\d(digit) and\w(word character) instead of typing out ranges. - Use quantifiers like
+(1 or more) or{n}(exactly n) to control repetition. - The
gflag finds all matches (global), and theiflag ignores case. - Use
regex.test(str)for true/false validation, andstr.match(regex)for extraction.
Done with this concept?
Mark it complete to track your progress. No login needed.