What Is a Regular Expression?
A regular expression (regex) is a sequence of characters that defines a search pattern. They are used for string searching, validation, parsing and text manipulation in virtually every programming language. In JavaScript, a regex is written between forward slashes: /pattern/flags.
Regex patterns can match simple literal text, or complex patterns like email addresses, URLs, phone numbers and dates using special metacharacters like \d, \w, +, *, ? and {n,m}.
JavaScript Regex Flags
| Flag | Name | Effect |
|---|---|---|
| g | Global | Find all matches instead of stopping after the first |
| i | Ignore case | Case-insensitive matching |
| m | Multiline | ^ and $ match start/end of each line |
| s | Dotall | Dot (.) matches newline characters too |
| u | Unicode | Enables full Unicode matching |
| y | Sticky | Matches only from the lastIndex position |
Common Regex Use Cases
- Email validation β
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} - URL matching β
https?:\/\/[^\s]+ - Phone numbers β
[\+]?[\d\s\-\(\)]{7,15} - IPv4 addresses β
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b - Dates (YYYY-MM-DD) β
\d{4}-\d{2}-\d{2} - Hex colors β
#[0-9a-fA-F]{3,6}