5 min read
•Question 40 of 50mediumHow do Regular Expressions work in JavaScript?
Understanding RegExp basics and common patterns.
What You'll Learn
- Creating regular expressions
- Common patterns
- Methods for matching
Creating RegExp
code.jsJavaScript
// Literal syntax
const regex1 = /pattern/flags;
// Constructor
const regex2 = new RegExp('pattern', 'flags');
// Flags
// g - global (find all)
// i - case insensitive
// m - multilineCommon Patterns
| Pattern | Meaning |
|---|---|
| . | Any character |
| \d | Digit [0-9] |
| \w | Word character [a-zA-Z0-9_] |
| \s | Whitespace |
| ^ | Start of string |
| $ | End of string |
| * | 0 or more |
| + | 1 or more |
| ? | 0 or 1 |
| {n} | Exactly n times |
| [abc] | Character class |
| (x) | Capturing group |
Methods
code.jsJavaScript
const text = 'The quick brown fox';
const regex = /quick/;
// test - returns boolean
regex.test(text); // true
// match - returns matches
text.match(/o/g); // ['o', 'o']
// replace
text.replace(/fox/, 'dog'); // 'The quick brown dog'
// exec - detailed match info
/quick/.exec(text);
// ['quick', index: 4, input: 'The quick brown fox']Practical Examples
code.jsJavaScript
// Email validation
const email = /^[\w.-]+@[\w.-]+\.\w+$/;
email.test('user@example.com'); // true
// Phone number
const phone = /^\d{3}-\d{3}-\d{4}$/;
phone.test('123-456-7890'); // true
// Extract numbers
'Price: $99.99'.match(/\d+\.?\d*/g); // ['99.99']
// Capture groups
const date = /^(\d{4})-(\d{2})-(\d{2})$/;
const [, year, month, day] = date.exec('2024-01-15');