These are the notes for JavaScript episode 23. A delivery app's sign-up form must accept only real Indian mobile numbers. The obvious check, s.length === 10 && !isNaN(s), lets "98765.4321", "0x12345678", " 987654321" and "1234567890" through, because it asks "is this a number?" instead of "does this text have the right shape?". You'll invent a tiny pattern language, the regular expression (regex), piece by piece: \d, [6-9], {9}, the anchors ^ and $, and test(). Then you'll find every number in a message with match and the g flag, mask numbers with replace and groups, pull a date apart with (named) groups, and learn the classic traps: the bare dot, the lastIndex trap and invalid patterns. Every output below is real Node.js output (node main.js).
Builds on: strings (episode 4), if/else (5), loops (6), arrays (7), functions (9), destructuring (12), try/catch (13), JSON (19), Map and Set (21).
The real-life idea: the courier clerk's glance
At a courier counter you write your mobile number. The clerk doesn't phone it to check; one glance at its shape is enough: ten digits, starting with 6, 7, 8 or 9. A dot in it? Rejected instantly. A regex is that glance, written down.
| Courier clerk | JavaScript |
|---|---|
| "It must look like this" | a regex: /^[6-9]\d{9}$/ |
| Glancing: right shape or not? | regex.test(text) → true / false |
| Highlighting every number in a letter | text.match(/.../g) |
| Blacking out numbers before sharing | text.replace(/.../g, "...") |
| Copying out just the day and month | capture groups ( ) |
The problem: checking the value, not the shape
function isPhone(s) {
return s.length === 10 && !isNaN(s);
}
console.log(isPhone("9876543210"));
console.log(isPhone("98765"));
console.log(isPhone("98765.4321"));
console.log(isPhone("0x12345678"));
console.log(isPhone(" 987654321"));
console.log(isPhone("1234567890"));
true
false
true
true
true
true
Four fake numbers pass. isNaN("98765.4321") is false because it's a decimal; "0x12345678" is a hexadecimal (base-16) number; isNaN ignores leading spaces; and nothing checks the first digit. Patching it means more ifs: no dot, no x, no space, first digit 6–9, every character a digit... long code describing something simple.
Why it failed: we tested the value ("can this be read as a number?"), but the rule is about the shape of the text.
The fix: a regular expression
A regular expression is a pattern that describes the shape of text. In JavaScript you write it between slashes, like a string between quotes.
| Piece | Means | Example |
|---|---|---|
\d |
one digit 0–9 | /\d/ matches "a1" |
[6-9] |
one character from the set (here 6, 7, 8 or 9) | [aeiou] a vowel |
{9} |
the thing before it, exactly 9 times | \d{9} |
^ |
the start of the text | ^9 text starts with 9 |
$ |
the end of the text | 0$ text ends with 0 |
Read /^[6-9]\d{9}$/ aloud: start, one digit from 6 to 9, nine more digits, end. Exactly ten digits and nothing else.
const phone = /^[6-9]\d{9}$/;
const tests = ["9876543210", "98765.4321", "0x12345678",
" 987654321", "1234567890", "98765432100"];
for (const t of tests) {
console.log(JSON.stringify(t), phone.test(t));
}
"9876543210" true
"98765.4321" false
"0x12345678" false
" 987654321" false
"1234567890" false
"98765432100" false
JSON.stringify(t) prints the string with quotes, so the leading space is visible.
Why ^ and $ matter (anchors)
const loose = /[6-9]\d{9}/;
console.log(loose.test("abc9876543210xyz"));
console.log(loose.test("998765432100"));
const strict = /^[6-9]\d{9}$/;
console.log(strict.test("abc9876543210xyz"));
const pin = /^[1-9]\d{5}$/;
console.log(pin.test("110001"), pin.test("011000"), pin.test("11001"));
true
true
false
true false false
Without anchors, test asks "is the pattern somewhere inside?". For validation, always anchor with ^ ... $. The PIN code pattern is six digits whose first is not 0.
Finding and replacing: match, the g flag, groups
| Method | Returns |
|---|---|
regex.test(text) |
true / false |
text.match(regex) (no g) |
the first match with details (index, groups), or null |
text.match(regex) with g |
an array of all matched strings, or null |
text.matchAll(regex) (needs g) |
an iterator of every match with its groups |
text.replace(regex, replacement) |
a new string (every match if g) |
text.split(regex) |
an array split wherever the pattern matches |
text.search(regex) |
index of the first match, or -1 |
const msg = "Call Asha at 9876543210 or Ravi at 8123456789. Office: 040-2345678";
console.log(msg.match(/[6-9]\d{9}/g));
const masked = msg.replace(/([6-9]\d)\d{6}(\d{2})/g, "$1XXXXXX$2");
console.log(masked);
[ '9876543210', '8123456789' ]
Call Asha at 98XXXXXX10 or Ravi at 81XXXXXX89. Office: 040-2345678
The g flag (global) means "every match, not just the first". The round brackets are capture groups: in the replacement, $1 and $2 put back what groups 1 and 2 matched. The landline starts with 0, so it isn't matched.
Capture groups and named groups
const date = "Delivery on 02-11-2026";
const m = date.match(/(\d{2})-(\d{2})-(\d{4})/);
console.log(m[0], "|", m[1], m[2], m[3]);
const n = date.match(/(?<day>\d{2})-(?<month>\d{2})-(?<year>\d{4})/);
console.log(n.groups);
console.log(n.groups.year);
02-11-2026 | 02 11 2026
[Object: null prototype] { day: '02', month: '11', year: '2026' }
2026
m[0] is the whole match; m[1], m[2]... are the groups. Named groups (?<name>...) appear on .groups, so you read groups.year instead of remembering "group 3".
More tools: matchAll, replace with a function, escaping user text
const text = "Asha: 9876543210, Ravi: 8123456789";
for (const m of text.matchAll(/(\w+): ([6-9]\d{9})/g)) console.log(m[1], "->", m[2], "at", m.index);
console.log("chai 20, samosa 15".replace(/\d+/g, (n) => n * 2));
function escapeRegex(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
const re = new RegExp(escapeRegex("(1+1)"));
console.log(re.source, re.test("is (1+1) = 2?"));
console.log("Masala Chai".search(/chai/i), "a.b.c".replaceAll(".", "-"));
Asha -> 9876543210 at 0
Ravi -> 8123456789 at 18
chai 40, samosa 30
\(1\+1\) true
7 a-b-c
matchAll returns an iterator (episode 22) of full matches. replace can take a function that receives each match and returns its replacement. new RegExp(string) builds a regex from a string; escapeRegex puts a backslash before every special character so user text is matched literally ($& means "the whole match").
The cheat sheet
| Piece | Means |
|---|---|
\d \w \s |
a digit · a word character (letter, digit, _) · a whitespace character |
\D \W \S |
NOT a digit · not a word character · not whitespace |
. |
any one character (except a newline) |
+ * ? |
one or more · zero or more · optional (zero or one) |
{3} {2,5} {2,} |
exactly 3 · 2 to 5 · 2 or more |
[abc] [a-z] [^abc] |
one of these · a range · anything except these |
^ $ |
start · end |
( ) (?<name> ) |
capture group · named group |
a\|b |
a or b |
\. \( \+ |
a literal dot, bracket, plus (escape special characters) |
flags g i m |
every match · ignore case · ^/$ per line |
console.log(/4.5/.test("price 435"));
console.log(/4\.5/.test("price 435"), /4\.5/.test("price 4.5"));
console.log(/chai/.test("Masala CHAI"), /chai/i.test("Masala CHAI"));
console.log("a1b22c333".replace(/\d+/g, "#"));
console.log("Asha, Ravi;Meena Kabir".split(/[,; ]+/));
true
false true
false true
a#b#c#
[ 'Asha', 'Ravi', 'Meena', 'Kabir' ]
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
s.length === 10 && !isNaN(s) |
"98765.4321" → true |
checks the value, not the shape | /^[6-9]\d{9}$/.test(s) |
/[6-9]\d{9}/.test(input) |
"abc9876543210xyz" → true |
no anchors: matches inside | /^...$/ |
/4.5/ |
matches "435" |
. means any character |
/4\.5/ |
const re = /chai/g; re.test("chai") three times |
true, false, true |
with g, the regex remembers lastIndex |
no g for test(), or reset re.lastIndex = 0 |
new RegExp("(") |
SyntaxError: Invalid regular expression: /(/: Unterminated group |
( is a special character |
escape user text, or try/catch |
"a-b-c".replace("-", "+") |
"a+b-c" |
a string pattern replaces only the first | /-/g or replaceAll |
text.match(/x/g).length when nothing matches |
TypeError: Cannot read properties of null (reading 'length') |
match returns null, not [] |
(text.match(/x/g) \|\| []).length |
"\d" in new RegExp("\d{6}") |
matches "dddddd" |
in a string, "\d" is just "d" |
new RegExp("\\d{6}") |
const re = /chai/g;
console.log(re.test("chai"));
console.log(re.test("chai"));
console.log(re.test("chai"));
true
false
true
const userInput = "(";
const re = new RegExp(userInput);
console.log(re.test("hello"));
const re = new RegExp(userInput);
^
SyntaxError: Invalid regular expression: /(/: Unterminated group
Mini project: a sign-up form validator
const rules = {
phone: /^[6-9]\d{9}$/,
pin: /^[1-9]\d{5}$/,
email: /^[\w.]+@[\w-]+\.[a-z]{2,}$/i,
};
function validate(form) {
const errors = [];
for (const [field, pattern] of Object.entries(rules)) {
if (!pattern.test(form[field].trim())) errors.push(field);
}
return errors.length ? "Fix: " + errors.join(", ") : "All good!";
}
console.log(validate({ phone: "9876543210", pin: "560001", email: "asha@mail.com" }));
console.log(validate({ phone: "98765.4321", pin: "056001", email: "asha@mail" }));
All good!
Fix: phone, pin, email
The email pattern is deliberately simple (letters, digits, _ or . before @, a domain, a dot, 2+ letters). Real email rules are far more complex; for real apps, check the basic shape and then send a confirmation email.
Practice
- Write a regex for a 6-digit OTP.
- Check an Indian vehicle number like
MH12AB1234: two capital letters, two digits, one or two capital letters, four digits. - Find every
#hashtagin a sentence. - Turn
"2026-11-02"into"02/11/2026"withreplaceand groups.
Solutions
- and 2. (and 3., 4.):
const otp = /^\d{6}$/;
console.log(otp.test("482913"), otp.test("48291"), otp.test("48a913"));
const vehicle = /^[A-Z]{2}\d{2}[A-Z]{1,2}\d{4}$/;
console.log(vehicle.test("MH12AB1234"), vehicle.test("DL3C4567"), vehicle.test("MH12AB123"));
console.log("Loving the #monsoon in #Mumbai #chai_time".match(/#\w+/g));
console.log("2026-11-02".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));
true false false
true false false
[ '#monsoon', '#Mumbai', '#chai_time' ]
02/11/2026
DL3C4567 fails because our rule asks for two digits after the state code.
Quick quiz
Which strings pass?
const pin = /^[1-9]\d{5}$/;
["560001", "056001", "5600011"]
.map(p => pin.test(p))
- A.
true false false - B.
true true false - C.
true true true - D.
false false false
Answer
A. Six digits, the first from 1 to 9. 056001 starts with 0, and 5600011 has seven digits, so $ rejects it.
Interview questions
- What is a regular expression? Give a real use.
- What's the difference between
test,match,matchAllandreplace? - What do
^and$do, and why are they essential for validation? - What does the
gflag change? Why cantest()withgreturn different answers for the same input? - What are capture groups? Named groups? How do you use them in
replace? - Why does
/4.5/match"435"? How do you match a literal dot? - What does
matchreturn when nothing matches? - How do you build a regex from user input safely?
- What are greedy quantifiers? (
+and*match as much as possible;+?and*?as little as possible.) - Why shouldn't you try to validate every possible email address with one regex?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Regular expression (regex) | a pattern that describes the shape of text | /^[6-9]\d{9}$/ |
| Regex literal | a regex written between slashes | /chai/i |
RegExp |
the regex constructor, building a pattern from a string | new RegExp("\\d+") |
| Validation | checking that input has an allowed shape | phone, PIN, OTP |
| Hexadecimal | base-16 numbers, written with 0x in JavaScript |
0x12345678 |
isNaN(x) |
true if x can't be read as a number |
isNaN("abc") → true |
| Character class | a set of allowed characters in [ ] |
[6-9], [aeiou] |
\d, \w, \s |
digit, word character, whitespace | \d{6} |
| Quantifier | how many times: +, *, ?, {n}, {n,m} |
\d{9} |
| Anchor | a position, not a character: ^ start, $ end |
^...$ |
| Match | a piece of text the pattern fits | "9876543210" |
| Flag | a letter after the closing slash that changes behaviour | g, i, m |
Global (g) flag |
find every match | match(/\d+/g) |
i flag |
ignore upper/lower case | /chai/i |
| Capture group | ( ): part of the pattern you can read back |
$1, m[1] |
| Named group | (?<name> ): a group read by name |
m.groups.year |
| Escape | a backslash that makes a special character literal | \., \( |
lastIndex |
where a g regex starts its next search |
the true/false/true trap |
| Literal | matched as itself, with no special meaning | \. matches a real dot |
Summary
- Checking a value (
isNaN) isn't checking a shape; a regex describes the shape. - Build patterns from pieces:
\d,[6-9],{9},+,*,?,., and anchor validation with^ ... $. test→ yes/no;matchwithg→ every match;replacewith groups and$1→ transformed text;splitwith a regex → clean pieces.- Groups
( )and named groups(?<name> )pull parts out. - Traps: a bare
.matches anything (\.),g+test()rememberslastIndex,matchcan returnnull, user text innew RegExpmust be escaped.
Next episode: The event loop. JavaScript runs one line at a time, so how does it wait for timers, files and the network without freezing?