About Lesson
Patterns and Flags:
Flags:
a) g (global):
Matches all occurrences of the pattern.
JavaScript
let text = "The cat is on the mat. Another cat is in the hat.";
let regex = /cat/g;
let result = text.match(regex);
console.log(result); // Output: ["cat", "cat"]
b) i (case-insensitive):
Ignores case.
JavaScript
let text = "Dog days are here. DOGS are wonderful.";
let regex = /dog/i;
let result = text.match(regex);
console.log(result); // Output: ["Dog"]
c) m (multiline):
Treats the string as multiple lines.
JavaScript
let text = `Hello world
Welcome to JavaScript
Learning is fun`;
let regex = /^Welcome/m;
let result = text.match(regex);
console.log(result); // Output: ["Welcome"]
d) s (dotAll):
Makes . match newline characters.
JavaScript
let text = `Dear User,
Thank you for signing up.
We hope you enjoy your experience.
Best Regards,
The Team`;
let regex = /Dear User.*experience/s; // Matches everything from "Dear User" to "experience"
let result = text.match(regex);
console.log(result);
// Output: ["Dear User,\nThank you for signing up.\nWe hope you enjoy your experience"]
Examples:
Example1: Validating Email Addresses
JavaScript
let emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
let email = "test@example.com";
console.log(emailRegex.test(email)); // true
Example 2: Extracting Numbers
JavaScript
let text = "There are 3 apples and 7 bananas.";
let regex = /\d+/g; // Matches all numbers globally
console.log(text.match(regex)); // Output: ["3", "7"]