The detective searches by description
Regular expressions, test, match, replace, the g and i flags, \d, \w, \s, quantifiers, ^ and $, groups.
includes is useless here: it looks for exact text, and I need a pattern — "digit, digit, dash…". That's what regular expressions are for.const note = "Suspect: a ginger cat, called from 555-123-4567";
console.log(/cat/.test(note));
console.log(/dog/.test(note));
console.log(/\d/.test(note));test answers: is there a match or not.A regular expression is a text pattern. Letters in it mean themselves, but some characters are commands:
\d— any digit,\D— any character except a digit;\s— a whitespace character (space, tab, line break);\w— a Latin letter, a digit or_;[abc]— one of the listed characters,[a-z]— any one from the range;.— literally any character (except a line break).
How many times to repeat a piece is told by quantifiers — they go right after it:
+— one or more:\d+is a number of any length;*— zero or more;?— zero or one, i.e. "optional":colou?rmatches both "color" and "colour";{3}— exactly three times,{2,4}— two to four times.
const report = "Witnesses: 3 cats, 12 mice and 1 vacuum";
console.log(report.match(/\d+/g));
console.log(report.match(/\d/g));
console.log(report.match(/dog/g));match with the g flag returns an array of every match. No matches gives null, not an empty array.The letters after the closing slash are flags:
g(global) — find every match, not just the first;i(ignore case) — treat capitals and lowercase as the same.
Familiar string methods understand regexes too: replace swaps out pattern matches, and with g — all of them at once.
const phone = "+1 (555) 123-4567";
console.log(phone.replace(/\D/g, ""));
const gossip = "Cat ate the fish. CAT denies it. cat stays silent.";
console.log(gossip.replace(/cat/gi, "***"));console.log("café au lait".match(/\w+/g));
console.log("café au lait".match(/[a-zé]+/g));
console.log("café au lait".match(/\p{L}+/gu));é in the class, the café loses its last letter.To validate input you need anchors: ^ is the start of the string, $ is its end. Without them, test looks for a match anywhere inside the text, and junk around it doesn't bother it.
const postcode = /^\d{6}$/;
console.log(postcode.test("101000"));
console.log(postcode.test("10100"));
console.log(postcode.test("code 101000"));
console.log(/\d{6}/.test("code 101000"));Finally, groups. Parentheses ( ) bundle a piece of the pattern and remember what it matched. In replace, the remembered parts are inserted as $1, $2… — in the order of the parentheses.
const date = "2026-10-15";
console.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1"));const postcode = /^\d{6}$/ reads far better than a mysterious line in the middle of your code.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.