Regular Expressions
📖 Concept
Regular expressions (regex) are patterns used to match character combinations in strings. They can look intimidating but are incredibly powerful for validation, search, and text processing.
Creating: /pattern/flags or new RegExp("pattern", "flags")
Flags: g (global), i (case-insensitive), m (multiline), s (dotAll), u (unicode)
Key methods: test(), match(), matchAll(), replace(), search(), split()
🏠 Real-world analogy: Regex is like a metal detector with adjustable sensitivity — you define the pattern (metal type), and it scans text to find all matches.
💻 Code Example
1// Basic patterns2const emailRegex = /^[\w.-]+@[\w.-]+\.\w{2,}$/i;3console.log(emailRegex.test("user@example.com")); // true45// Common patterns6const phoneRegex = /^\+?\d{1,3}[-.\s]?\d{3,4}[-.\s]?\d{4}$/;7const urlRegex = /^https?:\/\/[\w.-]+\.[a-z]{2,}/i;8const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;910// Methods11const str = "Hello World hello world";12console.log(str.match(/hello/gi)); // ["Hello", "hello"]13console.log(str.replace(/world/gi, "JS")); // "Hello JS hello JS"14console.log(str.search(/world/i)); // 61516// Groups and captures17const date = "2024-01-15";18const [, year, month, day] = date.match(/(\d{4})-(\d{2})-(\d{2})/);19console.log({ year, month, day });2021// Named groups22const dateMatch = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);23console.log(dateMatch.groups); // { year: "2024", month: "01", day: "15" }2425// Lookahead and lookbehind26const prices = "Item: $100, Tax: $15, Total: $115";27const amounts = prices.match(/(?<=\$)\d+/g); // ["100", "15", "115"]
🏋️ Practice Exercise
Mini Exercise:
- Write a regex to validate email addresses
- Write a regex to extract all hashtags from a tweet
- Create a function that converts camelCase to kebab-case
- Write a password strength validator using regex
⚠️ Common Mistakes
Forgetting to escape special characters:
.matches ANY character, use\.for a literal dotUsing greedy quantifiers (
.*) when lazy (.*?) is needed — greedy matches too muchNot using the
gflag when you need all matches, not just the firstForgetting that
^and$match start/end of string, not line (unlessmflag is used)Complex regex is hard to maintain — consider splitting into multiple simpler checks or use named groups
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Regular Expressions. Login to unlock this feature.