📜 Regular Expressions in JavaScript: A Complete Guide for Beginners to Pros! 🚀
Hey there, coders! 👋 Whether you're just starting out or you're a seasoned developer, Regular Expressions (RegEx) are like magic spells 🧙♂️ for working with text in JavaScript. Let's learn how to write them and use methods like match(), replace(), test(), and exec() with simple examples!
🌟 What is RegEx?
RegEx is a pattern that helps you search, match, or replace text in strings. Think of it as a "filter" 🔍 that can find phone numbers, emails, or even replace all "colour" with "color" in a document!
🛠️ Creating a RegEx in JavaScript
You can create a RegEx in two ways:
🔍 RegEx Methods in Action!
1. test(): Check if a Pattern Exists (True/False)
Example: Check if a string contains digits.
let regex = /\d+/; // \d = digit, + = one or more
console.log(regex.test("Age: 25")); // true 👍
console.log(regex.test("Hello World")); // false 👎
2. match(): Extract Matched Patterns
Example: Extract all numbers from a string.
let text = "Hello 123 World 456";
let matches = text.match(/\d+/g); // 'g' = global search
console.log(matches); // ["123", "456"] 🎉
3. replace(): Replace Matched Text
Example: Change "colour" to "color".
let text = "The colour of the sky is colourless.";
let newText = text.replace(/colour/g, "color");
console.log(newText); // "The color of the sky is colorless." 🖌️
4. exec(): Advanced Matching (Loop Through Results)
Example: Find one match at a time.
let regex = /\b\w+\b/g; // \b = word boundary, \w = word character
let text = "Hello World";
let result;
while ((result = regex.exec(text)) !== null) {
console.log("Found:", result[0]); // "Hello", then "World" 🔄
}
🧩 Common RegEx Patterns for Daily Use
Recommended by LinkedIn
A. Email Validation
let emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test("user@example.com")); // true ✅
console.log(emailRegex.test("user@.com")); // false ❌
B. Indian Phone Number (+91)
let phoneRegex = /^\+91\d{10}$/; // +91 followed by 10 digits
console.log(phoneRegex.test("+919876543210")); // true ✅
C. Remove Extra Spaces
let text = "Hello World! ";
let cleanText = text.replace(/\s+/g, " "); // Replace multiple spaces with one
console.log(cleanText); // "Hello World! " 🧹
🚀 Advanced RegEx Techniques
1. Groups (): Capture Parts of a Match
Example: Extract day, month, and year from a date.
let dateRegex = /(\d{2})-(\d{2})-(\d{4})/;
let date = "25-12-2023";
let match = dateRegex.exec(date);
console.log("Day:", match[1]); // 25 📅
console.log("Month:", match[2]); // 12
console.log("Year:", match[3]); // 2023
2. Lookaheads (?=): Match if Followed by a Pattern
Example: Password must have a capital letter and a number.
let passwordRegex = /^(?=.*[A-Z])(?=.*\d).{8,}$/;
console.log(passwordRegex.test("Secret123")); // true ✅
console.log(passwordRegex.test("weak")); // false ❌
3. Greedy vs. Lazy Quantifiers
Example: Extract content from HTML tags.
let html = "<div>Hello</div><div>World</div>";
// Greedy
console.log(html.match(/<div>(.*)<\/div>/)[1]); // "Hello</div><div>World" 😅
// Lazy
console.log(html.match(/<div>(.*?)<\/div>/)[1]); // "Hello" 🎯
💡 Pro Tips for RegEx Mastery
🎯 Conclusion
RegEx might seem scary at first, but with practice, you’ll be using it like a pro! 🏆 Start with simple patterns and gradually explore advanced techniques. Whether you’re validating forms, cleaning data, or parsing logs, RegEx is your best friend! 🤖
Happy Coding! 💻✨