Lesson 83 +20 XP

RegExp in Practice

Let's put regex to work with real examples.

Validate an email


js
let emailPattern = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
emailPattern.test("ada@example.com"); // true

Find all matches with g


js
let text = "cat hat bat";
text.match(/at/g); // ["at", "at", "at"]

Replace text


js
"hello world".replace(/world/, "JavaScript");
// "hello JavaScript"

Extract digits


js
"Order 42 shipped".match(/\d+/); // ["42"]

Check a phone-like pattern


js
/^\d{3}-\d{3}-\d{4}$/.test("123-456-7890"); // true

A validation helper


js
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.