Regular expressions (regex) are powerful patterns for matching, searching, and manipulating text. From validating email addresses to extracting phone numbers, from finding patterns in data to replacing text based on complex rules, regex is an essential tool in every developer's toolkit. While regex syntax can seem cryptic at first, learning the basics opens up a world of text processing possibilities. Let's master regular expressions!
What are Regular Expressions?
Regular Expressions (Regex):
- Patterns for matching character combinations in strings
- Used for validation, searching, and text manipulation
- Supported in JavaScript, Python, Java, and most languages
- Powerful but can be complex
- Essential for form validation, data parsing, text processing
// Creating regex patterns
// Method 1: Literal notation (most common)
let pattern1 = /hello/;
// Method 2: Constructor
let pattern2 = new RegExp('hello');
// Both create the same pattern
console.log(pattern1); // /hello/
console.log(pattern2); // /hello/
// Use literal for static patterns
let emailPattern = /^[\w-\.]+@[\w-]+\.[a-z]{2,}$/;
// Use constructor for dynamic patterns
let searchTerm = 'world';
let dynamicPattern = new RegExp(searchTerm); // Pattern based on variableBasic Regex Methods
test() - Check if Pattern Matches
// test() returns true/false
let pattern = /hello/;
console.log(pattern.test('hello world')); // true
console.log(pattern.test('Hello world')); // false (case-sensitive)
console.log(pattern.test('hi there')); // false
// Practical: Validate format
let hasNumber = /\d/; // \d matches any digit
console.log(hasNumber.test('abc123')); // true
console.log(hasNumber.test('abc')); // false
// Check if string contains only letters
let onlyLetters = /^[a-zA-Z]+$/;
console.log(onlyLetters.test('hello')); // true
console.log(onlyLetters.test('hello123')); // false
// Validate email (basic)
let emailPattern = /@/;
console.log(emailPattern.test('user@example.com')); // true
console.log(emailPattern.test('invalid')); // falsematch() - Find Matches
// match() returns array of matches or null
let text = 'The phone numbers are 123-456-7890 and 987-654-3210';
// Without 'g' flag - returns first match with details
let pattern1 = /\d{3}-\d{3}-\d{4}/;
let result1 = text.match(pattern1);
console.log(result1);
// ['123-456-7890', index: 22, input: '...', groups: undefined]
console.log(result1[0]); // '123-456-7890'
// With 'g' flag - returns all matches
let pattern2 = /\d{3}-\d{3}-\d{4}/g;
let result2 = text.match(pattern2);
console.log(result2);
// ['123-456-7890', '987-654-3210']
// No match returns null
let noMatch = text.match(/xyz/);
console.log(noMatch); // null
// Extract words
let sentence = 'Hello world, how are you?';
let words = sentence.match(/\w+/g);
console.log(words);
// ['Hello', 'world', 'how', 'are', 'you']
// Extract numbers
let numbers = 'I have 5 apples and 10 oranges'.match(/\d+/g);
console.log(numbers); // ['5', '10']replace() - Replace Matches
// replace() replaces matched text
let text = 'Hello world, hello everyone';
// Replace first match
let result1 = text.replace(/hello/i, 'Hi');
console.log(result1); // "Hi world, hello everyone"
// Replace all matches (use 'g' flag)
let result2 = text.replace(/hello/gi, 'Hi');
console.log(result2); // "Hi world, Hi everyone"
// Replace with function
let numbers = 'I have 5 apples and 10 oranges';
let doubled = numbers.replace(/\d+/g, (match) => {
return match * 2;
});
console.log(doubled); // "I have 10 apples and 20 oranges"
// Censor words
let message = 'This is bad and terrible';
let censored = message.replace(/bad|terrible/gi, '***');
console.log(censored); // "This is *** and ***"
// Format phone number
let phone = '1234567890';
let formatted = phone.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
console.log(formatted); // "(123) 456-7890"split() - Split String by Pattern
// split() with regex
let text = 'apple,banana;orange|grape';
// Split by multiple delimiters
let fruits = text.split(/[,;|]/);
console.log(fruits);
// ['apple', 'banana', 'orange', 'grape']
// Split by whitespace (including multiple spaces)
let sentence = 'Hello world how are you';
let words = sentence.split(/\s+/);
console.log(words);
// ['Hello', 'world', 'how', 'are', 'you']
// Split but keep delimiter
let text2 = 'Hello. How are you? I am fine!';
let sentences = text2.split(/([.?!])/);
console.log(sentences);
// ['Hello', '.', ' How are you', '?', ' I am fine', '!', '']Basic Pattern Syntax
Literal Characters
// Exact match
/hello/.test('hello'); // true
/hello/.test('Hello'); // false (case-sensitive)
/hello/.test('hello world'); // true (contains 'hello')
// Multiple characters
/cat/.test('I have a cat'); // true
/dog/.test('I have a cat'); // falseCharacter Classes
// [abc] - matches any single character in brackets
/[aeiou]/.test('hello'); // true (matches 'e' and 'o')
/[0-9]/.test('abc'); // false
/[0-9]/.test('abc3'); // true
// [^abc] - matches any character NOT in brackets
/[^0-9]/.test('123'); // false (all are digits)
/[^0-9]/.test('abc'); // true
// Ranges
/[a-z]/.test('Hello'); // true (matches lowercase letters)
/[A-Z]/.test('hello'); // false
/[a-zA-Z]/.test('Hello'); // true (matches any letter)
/[0-9]/.test('5'); // true (matches any digit)Special Characters
// \d - digit (0-9)
/\d/.test('abc123'); // true
// \D - NOT digit
/\D/.test('123'); // false
/\D/.test('abc'); // true
// \w - word character (letter, digit, underscore)
/\w/.test('hello'); // true
/\w/.test('_test'); // true
/\w/.test('@'); // false
// \W - NOT word character
/\W/.test('hello'); // false
/\W/.test('@'); // true
// \s - whitespace (space, tab, newline)
/\s/.test('hello world'); // true
/\s/.test('hello'); // false
// \S - NOT whitespace
/\S/.test(' '); // false
/\S/.test('a'); // true
// . - any character except newline
/./.test('a'); // true
/./.test('5'); // true
/./.test('@'); // trueQuantifiers
// + - one or more
/\d+/.test('123'); // true
/\d+/.test('abc'); // false
'abc123'.match(/\d+/); // ['123']
// * - zero or more
/\d*/.test('abc'); // true (zero digits is OK)
/\d*/.test('123'); // true
// ? - zero or one (optional)
/colou?r/.test('color'); // true
/colou?r/.test('colour'); // true
// {n} - exactly n times
/\d{3}/.test('12'); // false
/\d{3}/.test('123'); // true
/\d{3}/.test('1234'); // true (has at least 3)
// {n,} - n or more times
/\d{3,}/.test('12'); // false
/\d{3,}/.test('123'); // true
/\d{3,}/.test('12345'); // true
// {n,m} - between n and m times
/\d{2,4}/.test('1'); // false
/\d{2,4}/.test('12'); // true
/\d{2,4}/.test('123'); // true
/\d{2,4}/.test('1234'); // true
/\d{2,4}/.test('12345'); // true (has at least 2)Anchors
// ^ - start of string
/^hello/.test('hello world'); // true
/^hello/.test('say hello'); // false
// $ - end of string
/world$/.test('hello world'); // true
/world$/.test('world hello'); // false
// ^...$ - exact match (start to end)
/^hello$/.test('hello'); // true
/^hello$/.test('hello world'); // false
/^hello$/.test('say hello'); // false
// Practical: Validate exact format
let zipCode = /^\d{5}$/;
console.log(zipCode.test('12345')); // true
console.log(zipCode.test('1234')); // false
console.log(zipCode.test('123456')); // falseRegex Flags
// i - case-insensitive
/hello/i.test('HELLO'); // true
/hello/i.test('Hello'); // true
// g - global (find all matches)
'hello hello'.match(/hello/); // ['hello'] (first only)
'hello hello'.match(/hello/g); // ['hello', 'hello'] (all)
// m - multiline (^ and $ match line breaks)
let text = `line1
line2
line3`;
/^line2/.test(text); // false (^ only matches start of string)
/^line2/m.test(text); // true (^ matches start of any line)
// Combine flags
/hello/gi.test('HELLO'); // true (case-insensitive + global)
// s - dotAll (. matches newlines)
/.+/.test('a\nb'); // false (. doesn't match \n)
/.+/s.test('a\nb'); // true (. matches everything)
// u - unicode
/\u{1F600}/u.test('😀'); // true (emoji support)Common Validation Patterns
Email Validation
// Simple email validation
let emailPattern = /^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i;
console.log(emailPattern.test('user@example.com')); // true
console.log(emailPattern.test('user.name@test.co.uk')); // true
console.log(emailPattern.test('invalid@')); // false
console.log(emailPattern.test('@example.com')); // false
// More comprehensive (still not perfect for all cases)
let betterEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
function validateEmail(email) {
return betterEmail.test(email);
}
console.log(validateEmail('test@gmail.com')); // true
console.log(validateEmail('test+tag@domain.co')); // true
console.log(validateEmail('invalid.email')); // falsePhone Number Validation
// US phone number formats
let phone1 = /^\d{10}$/; // 1234567890
let phone2 = /^\d{3}-\d{3}-\d{4}$/; // 123-456-7890
let phone3 = /^\(\d{3}\) \d{3}-\d{4}$/; // (123) 456-7890
console.log(phone1.test('1234567890')); // true
console.log(phone2.test('123-456-7890')); // true
console.log(phone3.test('(123) 456-7890')); // true
// Flexible phone validator (multiple formats)
let flexiblePhone = /^(\d{10}|\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4})$/;
function validatePhone(phone) {
return flexiblePhone.test(phone);
}
console.log(validatePhone('1234567890')); // true
console.log(validatePhone('123-456-7890')); // true
console.log(validatePhone('(123) 456-7890')); // true
console.log(validatePhone('12345')); // falseURL Validation
// Basic URL validation
let urlPattern = /^https?:\/\/[\w.-]+\.[a-z]{2,}(:[0-9]+)?(\/.*)?$/i;
console.log(urlPattern.test('http://example.com')); // true
console.log(urlPattern.test('https://www.google.com')); // true
console.log(urlPattern.test('https://site.com:8080/path')); // true
console.log(urlPattern.test('not-a-url')); // false
function validateURL(url) {
return urlPattern.test(url);
}
console.log(validateURL('https://falytom.com.ng')); // true
console.log(validateURL('ftp://example.com')); // false (not http/https)Password Strength
// Password requirements:
// - At least 8 characters
// - Contains uppercase
// - Contains lowercase
// - Contains digit
// - Contains special character
function validatePassword(password) {
let minLength = /.{8,}/;
let hasUpper = /[A-Z]/;
let hasLower = /[a-z]/;
let hasDigit = /\d/;
let hasSpecial = /[!@#$%^&*(),.?":{}|<>]/;
return (
minLength.test(password) &&
hasUpper.test(password) &&
hasLower.test(password) &&
hasDigit.test(password) &&
hasSpecial.test(password)
);
}
console.log(validatePassword('Pass123!')); // true
console.log(validatePassword('weakpass')); // false
console.log(validatePassword('NoDigit!')); // false
// All-in-one pattern (more complex)
let strongPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
console.log(strongPassword.test('Pass123!')); // true
console.log(strongPassword.test('weak')); // falseDate Formats
// MM/DD/YYYY
let usDate = /^\d{2}\/\d{2}\/\d{4}$/;
console.log(usDate.test('12/31/2024')); // true
console.log(usDate.test('2024-12-31')); // false
// YYYY-MM-DD (ISO format)
let isoDate = /^\d{4}-\d{2}-\d{2}$/;
console.log(isoDate.test('2024-12-31')); // true
console.log(isoDate.test('12/31/2024')); // false
// Flexible date validator
function validateDate(date) {
let us = /^(0?[1-9]|1[0-2])\/(0?[1-9]|[12][0-9]|3[01])\/\d{4}$/;
let iso = /^\d{4}-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01])$/;
return us.test(date) || iso.test(date);
}
console.log(validateDate('12/31/2024')); // true
console.log(validateDate('2024-12-31')); // true
console.log(validateDate('invalid')); // falsePractical Examples
Example 1: Form Validation
// Complete form validator
class FormValidator {
static patterns = {
email: /^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i,
phone: /^\d{10}$/,
zipCode: /^\d{5}(-\d{4})?$/,
username: /^[a-zA-Z0-9_]{3,20}$/,
url: /^https?:\/\/[\w.-]+\.[a-z]{2,}/i
};
static validate(field, value) {
let pattern = this.patterns[field];
if (!pattern) {
return { valid: false, error: 'Unknown field type' };
}
let valid = pattern.test(value);
return {
valid,
error: valid ? null : `Invalid ${field} format`
};
}
static validateForm(data) {
let errors = {};
for (let field in data) {
let result = this.validate(field, data[field]);
if (!result.valid) {
errors[field] = result.error;
}
}
return {
valid: Object.keys(errors).length === 0,
errors
};
}
}
// Usage
let formData = {
email: 'user@example.com',
phone: '1234567890',
zipCode: '12345',
username: 'john_doe'
};
let result = FormValidator.validateForm(formData);
if (result.valid) {
console.log('Form is valid!');
} else {
console.log('Errors:', result.errors);
}Example 2: Text Processing
// Extract and process data from text
class TextProcessor {
// Extract all emails
static extractEmails(text) {
let pattern = /[\w.-]+@[\w.-]+\.[a-z]{2,}/gi;
return text.match(pattern) || [];
}
// Extract all phone numbers
static extractPhones(text) {
let pattern = /\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4}|\d{10}/g;
return text.match(pattern) || [];
}
// Extract URLs
static extractURLs(text) {
let pattern = /https?:\/\/[\w.-]+\.[a-z]{2,}[^\s]*/gi;
return text.match(pattern) || [];
}
// Redact emails
static redactEmails(text) {
return text.replace(/[\w.-]+@[\w.-]+\.[a-z]{2,}/gi, '[EMAIL REDACTED]');
}
// Highlight mentions
static highlightMentions(text) {
return text.replace(/@(\w+)/g, '<strong>@$1</strong>');
}
// Remove extra whitespace
static normalizeWhitespace(text) {
return text.replace(/\s+/g, ' ').trim();
}
}
// Usage
let text = `
Contact us at support@example.com or sales@company.com
Call 123-456-7890 or (987) 654-3210
Visit https://example.com for more info
Hey @john and @jane, check this out!
`;
console.log('Emails:', TextProcessor.extractEmails(text));
console.log('Phones:', TextProcessor.extractPhones(text));
console.log('URLs:', TextProcessor.extractURLs(text));
console.log('Redacted:', TextProcessor.redactEmails(text));Regular Expressions Mastery
Master pattern matching
console.log() to see your output in the console above.Key Takeaways
- Regex are patterns for matching text
test()returns true/false for pattern matchmatch()returns array of matchesreplace()replaces matched text\dmatches digits,\wword characters,\swhitespace+one or more,*zero or more,?optional^start,$end of string- Flags:
icase-insensitive,gglobal,mmultiline - Use regex for validation, searching, text manipulation
- Practice makes perfect—regex gets easier with use
What's Next?
Congratulations! You've completed the Advanced Concepts section and now understand regular expressions! You've learned pattern matching, validation, and text manipulation with regex. These skills are essential for form validation, data processing, and text analysis.
You've now completed 59 out of 62 JavaScript tutorial pages (95% complete)! You're in the final stretch—just 3 more pages to go! Outstanding progress!
💪 Practice Challenge:
Before moving on, try:
- Create email and phone number validators
- Extract all URLs from a block of text
- Build a password strength validator
- Replace all mentions (@username) with links
- Validate date formats with regex