Loading lessons...
RegExp in Practice
RegExp in Practice
Let's put regex to work with real examples.
Validate an email
let emailPattern = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
emailPattern.test("ada@example.com"); // true
Find all matches with g
let text = "cat hat bat";
text.match(/at/g); // ["at", "at", "at"]
Replace text
"hello world".replace(/world/, "JavaScript");
// "hello JavaScript"
Extract digits
"Order 42 shipped".match(/\d+/); // ["42"]
Check a phone-like pattern
/^\d{3}-\d{3}-\d{4}$/.test("123-456-7890"); // true
A validation helper
function isEmail(value) {
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value);
}
TL;DR
- Use regex for email and format validation.
- The g flag with match gets all matches.
- replace() swaps matched text.
- String patterns like \d+ extract numbers.