Regular expressions (regex) are patterns used to match character combinations in strings. They’re powerful for validation, searching, and replacing text.
Creating Regular Expressions
Literal Syntax
const regex = /hello/;
const regex2 = /hello/i; // Case-insensitive
const regex3 = /hello/g; // Global
const regex4 = /hello/gi; // Global and case-insensitive
Constructor Syntax
const regex = new RegExp("hello");
const regex2 = new RegExp("hello", "i");
const regex3 = new RegExp("hello", "gi");
Flags
| Flag | Meaning |
|---|---|
i |
Case-insensitive |
g |
Global (find all) |
m |
Multiline |
s |
Dotall (. matches newlines) |
u |
Unicode |
y |
Sticky |
Basic Patterns
Literal Characters
const regex = /hello/;
console.log(regex.test("hello world")); // true
console.log(regex.test("Hello world")); // false
Character Classes
const regex1 = /[abc]/; // Matches a, b, or c
const regex2 = /[a-z]/; // Matches any lowercase letter
const regex3 = /[0-9]/; // Matches any digit
const regex4 = /[^abc]/; // Matches anything except a, b, c
Shorthand Classes
const regex1 = /\d/; // Digit [0-9]
const regex2 = /\D/; // Non-digit [^0-9]
const regex3 = /\w/; // Word character [a-zA-Z0-9_]
const regex4 = /\W/; // Non-word character
const regex5 = /\s/; // Whitespace
const regex6 = /\S/; // Non-whitespace
Quantifiers
const regex1 = /a*/; // 0 or more
const regex2 = /a+/; // 1 or more
const regex3 = /a?/; // 0 or 1
const regex4 = /a{3}/; // Exactly 3
const regex5 = /a{2,4}/; // 2 to 4
const regex6 = /a{2,}/; // 2 or more
Anchors
const regex1 = /^hello/; // Starts with hello
const regex2 = /world$/; // Ends with world
const regex3 = /^hello world$/; // Exact match
String Methods
test()
Check if pattern matches:
const regex = /hello/i;
console.log(regex.test("Hello World")); // true
console.log(regex.test("Goodbye")); // false
match()
Find matches:
const str = "The numbers are 123 and 456";
const matches = str.match(/\d+/g);
console.log(matches); // ["123", "456"]
search()
Find index of first match:
const str = "Hello World";
console.log(str.search(/world/i)); // 6
console.log(str.search(/xyz/)); // -1
replace()
Replace matches:
const str = "Hello World";
console.log(str.replace(/world/i, "JavaScript")); // "Hello JavaScript"
console.log(str.replace(/l/g, "L")); // "HeLLo WorLd"
replaceAll()
Replace all matches:
const str = "apple apple apple";
console.log(str.replaceAll("apple", "orange")); // "orange orange orange"
split()
Split by pattern:
const str = "apple,banana;orange:grape";
const fruits = str.split(/[,;:]/);
console.log(fruits); // ["apple", "banana", "orange", "grape"]
Practical Examples
Email Validation
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("invalid.email")); // false
Phone Number Validation
function isValidPhone(phone) {
const regex = /^\d{3}-\d{3}-\d{4}$/;
return regex.test(phone);
}
console.log(isValidPhone("123-456-7890")); // true
console.log(isValidPhone("1234567890")); // false
URL Validation
function isValidURL(url) {
const regex = /^https?:\/\/.+\..+/;
return regex.test(url);
}
console.log(isValidURL("https://example.com")); // true
console.log(isValidURL("not a url")); // false
Extract Domain from Email
function extractDomain(email) {
const match = email.match(/@(.+)$/);
return match ? match[1] : null;
}
console.log(extractDomain("[email protected]")); // "example.com"
Capitalize Words
function capitalizeWords(str) {
return str.replace(/\b\w/g, char => char.toUpperCase());
}
console.log(capitalizeWords("hello world")); // "Hello World"
Remove HTML Tags
function stripHTML(html) {
return html.replace(/<[^>]*>/g, "");
}
console.log(stripHTML("<p>Hello <b>World</b></p>")); // "Hello World"
Extract Numbers
function extractNumbers(str) {
return str.match(/\d+/g).map(Number);
}
console.log(extractNumbers("I have 2 apples and 5 oranges")); // [2, 5]
Password Validation
function isStrongPassword(password) {
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
return regex.test(password);
}
console.log(isStrongPassword("Weak")); // false
console.log(isStrongPassword("Strong@123")); // true
URL Slug Generation
function generateSlug(title) {
return title
.toLowerCase()
.trim()
.replace(/\s+/g, "-")
.replace(/[^\w-]/g, "");
}
console.log(generateSlug("Hello World!")); // "hello-world"
Advanced Patterns
Groups and Capturing
const regex = /(\d{3})-(\d{3})-(\d{4})/;
const match = "123-456-7890".match(regex);
console.log(match[1]); // "123"
console.log(match[2]); // "456"
console.log(match[3]); // "7890"
Non-Capturing Groups
const regex = /(?:cat|dog)/;
const match = "I have a cat".match(regex);
console.log(match[0]); // "cat"
Lookahead and Lookbehind
// Positive lookahead
const regex1 = /\d+(?=px)/;
console.log("100px".match(regex1)); // ["100"]
// Negative lookahead
const regex2 = /\d+(?!px)/;
console.log("100".match(regex2)); // ["100"]
Performance Tips
Use Specific Patterns
// Good - specific pattern
const regex = /^[a-z]+@[a-z]+\.[a-z]+$/;
// Avoid - too broad
const regex2 = /.+@.+\..+/;
Avoid Backtracking
// Good - specific
const regex = /^[a-z]{3}$/;
// Avoid - excessive backtracking
const regex2 = /^[a-z]*[a-z]*[a-z]*$/;
Summary
- Literal:
/pattern/ - Constructor:
new RegExp("pattern") - Flags: i (case-insensitive), g (global), m (multiline)
- Character classes:
[abc],[a-z],\d,\w,\s - Quantifiers:
*,+,?,{n},{n,m} - Anchors:
^,$ - Methods: test(), match(), search(), replace(), split()
- Best practice: use specific patterns, avoid backtracking
Related Resources
Official Documentation
Next Steps
- Form Handling and Validation
- Input Validation and Sanitization
- JavaScript Strings: Creation, Manipulation, Template Literals
Comments