Using Regular Expressions Effectively in Frontend Development
Abdelatif Baha
Paris, FRANCE
Regular Expressions for Frontend Developers
Regular expressions (regex) are powerful tools for pattern matching and text manipulation. Frontend developers use them for validation, parsing, and data transformation.
Regex Basics
A regex pattern matches text based on rules:
const pattern = /hello/;
console.log(pattern.test("hello world")); // true
Common Use Cases in Frontend
Email Validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function isValidEmail(email) {
return emailRegex.test(email);
}
console.log(isValidEmail("user@example.com")); // true
console.log(isValidEmail("invalid.email")); // false
Phone Number Formatting
function formatPhoneNumber(phone) {
const cleaned = phone.replace(/\D/g, '');
const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`;
}
return phone;
}
console.log(formatPhoneNumber("1234567890")); // "(123) 456-7890"
Password Strength
function checkPasswordStrength(password) {
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumber = /[0-9]/.test(password);
const hasSpecialChar = /[!@#$%^&*]/.test(password);
const isLongEnough = password.length >= 8;
return hasUpperCase && hasLowerCase && hasNumber && hasSpecialChar && isLongEnough;
}
URL Extraction
const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;
const text = "Visit https://example.com and https://google.com";
const urls = text.match(urlRegex);
console.log(urls); // ["https://example.com", "https://google.com"]
Advanced Techniques
Named Capturing Groups
const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = "2024-01-15".match(dateRegex);
console.log(match.groups.year); // "2024"
console.log(match.groups.month); // "01"
console.log(match.groups.day); // "15"
Performance Tips
- - Store regex in constants
Comments (0)