Summary - RegExp basics
Build a validation function that extracts email-like addresses from text using regex.
Summary - RegExp basics
In this group you met the basics of regular expressions: literals like /cat/, the new RegExp() constructor, the \d \w \s character classes, and the * + ? and {n} quantifiers.
You also learned to check a match with .test(), extract matches with .match(), and process strings with .replace() and .split(). Now you will combine them in one task.
Task setup
Two small tasks await. First, pull email-like addresses out of a text with .match(). Use \w+ for the user name, then @, then [\w.]+ for the domain.
Next, strip every non-digit character from a phone string with .replace() and keep only the digits. Hint: \D matches non-digits.
Exercise Extract email addresses
Assign all email-like addresses in the text to emails using text.match(). Use the pattern \w+@[\w.]+ and add the global flag. Log the result with console.log.
Show example solution
The match method with the g flag returns all matches. Use \w+ for the user name, then @, then [\w.]+ for the domain.
Example solution:
let emails = text.match(/\w+@[\w.]+/g);
console.log(emails);
Exercise Reduce a phone to digits
Assign the result of phone.replace() to digits, removing every non-digit character. Use the \D class with the global flag and replace with an empty string. Log the result with console.log.
Show example solution
replace takes a regex and a string. Use \D for non-digits and the g flag for all. Pass an empty string "" to remove them.
Example solution:
let digits = phone.replace(/\D/g, "");
console.log(digits);
Test yourself
-
Which pattern matches exactly 4 digits?
- /\d/
- /\d+/
- /\d?/
- /\d{4}/
Show answer
/\d{4}/ — Correct! /\d{4}/ matches exactly 4 digits.