Day 24 Regular Expressions (Regex)
Regular Expressions (Regex) patterns hote hain jo text mein match dhundne ke liye use hote hain. Email validate karna, phone number check karna, text search karna — regex se sab hota hai.
Regex Basics
Regex / / ke beech likhte hain. test() method match check karta hai, match() matches return karta hai.
// Pattern create karo
let pattern = /hello/;
console.log(pattern.test("say hello world")); // true
console.log(pattern.test("goodbye")); // false
// Flags:
// i = case insensitive, g = global (all matches)
let re = /javascript/i;
console.log(re.test("I love JavaScript")); // true
// Match find karo
let str = "My phone: 0300-1234567";
let match = str.match(/d{4}-d{7}/);
console.log(match[0]); // "0300-1234567"
// Replace karo
let result = "Hello World".replace(/World/, "Pakistan");
console.log(result); // "Hello Pakistan"
Common Patterns
Email, phone, URL validate karne ke liye common regex patterns.
// Email validate
function isValidEmail(email) {
return /^[^s@]+@[^s@]+.[^s@]+$/.test(email);
}
console.log(isValidEmail("test@gmail.com")); // true
console.log(isValidEmail("invalid-email")); // false
// Pakistan phone number
function isValidPhone(phone) {
return /^03d{9}$/.test(phone.replace(/-/g, ""));
}
console.log(isValidPhone("0300-1234567")); // true
// Strong password (8+ chars, number, uppercase)
function isStrongPassword(pass) {
return /^(?=.*[A-Z])(?=.*d).{8,}$/.test(pass);
}
console.log(isStrongPassword("MyPass123")); // true
console.log(isStrongPassword("weak")); // false
🎯 Practice Challenge
Form validator banao — email, phone (03XX-XXXXXXX), aur password (8+ chars, uppercase, number) validate karo with regex.