Home › Learn › JavaScript › Strings and numbers

Regular expressions

Lesson 30 of 40. Find and replace patterns in text.

A regular expression between slashes describes a pattern: \d a digit, \w a word character, \s whitespace, + one or more, * zero or more, ? optional, [a-z] a range, ^ and $ the start and end, \b a word boundary. Flags after the closing slash change behavior: g for all matches, i to ignore case.

re.test(text) asks yes or no; text.match(/\d+/g) returns all matches (or null); text.replace(re, replacement) substitutes (replaceAll needs the g flag). To put a variable into a pattern, build it with new RegExp(string, flags) and escape special characters first.

console.log(/^\d{4}-\d{2}-\d{2}$/.test("2026-03-15"));   // true
console.log("3 cats, 12 dogs".match(/\d+/g));            // ["3", "12"]
console.log("too   many".replace(/\s+/g, " "));

Your task

Write findNumbers(text) returning every run of digits as numbers, isEmailLike(text) returning whether the whole string looks like something@something.something (letters, digits, dots, underscores, hyphens on both sides), and censor(text, word) replacing every whole-word occurrence of word, ignoring case, with ***.

Hint 1

(text.match(/\d+/g) ?? []).map(Number)

Hint 2

/^[\w.-]+@[\w-]+\.[\w.-]+$/.test(text); censor: new RegExp("\\b" + word + "\\b", "gi")

Show the solution
function findNumbers(text) {
  return (text.match(/\d+/g) ?? []).map(Number);
}

function isEmailLike(text) {
  return /^[\w.-]+@[\w-]+\.[\w.-]+$/.test(text);
}

function censor(text, word) {
  return text.replace(new RegExp("\\b" + word + "\\b", "gi"), "***");
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.