RegExp Methods
A regular expression does nothing on its own; you use it through methods. Two belong to the regex itself (test and exec), and the rest belong to strings (match, matchAll, search, replace, replaceAll and split). Each answers a different question, from "does it match?" to "give me every match with its groups" to "replace each match with something computed". This lesson covers them all, plus RegExp.escape (ES2025) for building patterns from user input safely, and the limits of using regular expressions to validate real-world data.
In One Minute
re.test(str): does it match? (true/false)str.match(re): the first match with groups, or withg, an array of all matched strings (ornull).str.matchAll(re): every match with its groups (needsg); loop withfor...of.str.replace(re, replacement)andreplaceAll: replacement can be a string with$1/$<name>, or a function.RegExp.escape(text)makes user text safe to put inside a pattern.
Method Table
| Method | Belongs to | Returns |
|---|---|---|
re.test(str) | RegExp | true or false |
re.exec(str) | RegExp | One match array with groups, or null; with g/y, the next match from lastIndex |
str.match(re) | String | Without g: one match array with groups, or null. With g: array of matched strings, or null |
str.matchAll(re) | String | An iterator of match arrays with groups (re must have g) |
str.search(re) | String | Index of the first match, or -1 |
str.replace(re, rep) | String | New string; replaces the first match, or all with g |
str.replaceAll(re, rep) | String | New string; replaces all (re must have g) |
str.split(re, limit) | String | Array of the pieces between matches |
RegExp.escape(str) | RegExp (static) | The string with every special character escaped (ES2025) |
test: Does It Match?
const ZIP = /^\d{5}(?:-\d{4})?$/;
console.log(ZIP.test("75201"), ZIP.test("7520"), ZIP.test("94103-1234"));true false truetest is the right method for validation and if conditions.
The lastIndex Trap
A regex with the g or y flag is stateful: test and exec remember where the last match ended in the lastIndex property and continue from there next time. Reusing such a regex across different strings gives confusing results:
const HAS_DIGIT = /\d/g;
console.log(HAS_DIGIT.test("fee 120"));
console.log(HAS_DIGIT.lastIndex);
console.log(HAS_DIGIT.test("lab 45"));
console.log(HAS_DIGIT.test("lab 45"));true
5
true
falseExplanation: after the first match, lastIndex is 5, so the second test starts searching "lab 45" at index 5 and finds the "5". The third starts after that, finds nothing, returns false, and resets lastIndex to 0. The same string gave two different answers.
match and matchAll
const text = "Navika paid $120 on 01/05; Advitha paid $45 on 01/20.";
const PAYMENT = /(?<name>[A-Z]\w+) paid \$(?<amount>\d+)/;
const first = text.match(PAYMENT);
console.log(first[0], "|", first.groups.name, first.groups.amount);
console.log(text.match(/\$\d+/g));
console.log("no money here".match(/\$\d+/g));
for (const m of text.matchAll(new RegExp(PAYMENT, "g"))) {
console.log(`${m.groups.name}: $${m.groups.amount} at index ${m.index}`);
}Navika paid $120 | Navika 120
['$120', '$45']
null
Navika: $120 at index 0
Advitha: $45 at index 27Explanation:
- Without
g,matchreturns the first match with its groups and index. - With
g, it returns only the matched strings, andnullwhen nothing matches (not an empty array). matchAllreturns every match with groups and index. Its regex must haveg(it throws aTypeErrorotherwise).new RegExp(PAYMENT, "g")copies an existing regex with new flags.
replace and replaceAll
The replacement can be a string with special patterns, or a function.
Replacement Patterns
| Pattern | Inserts |
|---|---|
$& | The whole match |
$1, $2... | A numbered group |
$<name> | A named group |
$` / $' | The text before / after the match |
$$ | A literal $ |
const phone = "214.555.0100";
console.log(phone.replace(/\./, "-"));
console.log(phone.replace(/\./g, "-"));
console.log(phone.replaceAll(".", "-"));
console.log(phone.replace(/^(\d{3})\.(\d{3})\.(\d{4})$/, "($1) $2-$3"));
console.log("2026-01-05".replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "$<m>/$<d>/$<y>"));
console.log("Total 120".replace(/\d+/, "$$$&.00"));214-555.0100
214-555-0100
214-555-0100
(214) 555-0100
01/05/2026
Total $120.00replace with a plain string, or a regex without g, changes only the first match. replaceAll with a plain string changes every occurrence; with a regex, it requires the g flag.
Replacement Functions
When the replacement must be computed, pass a function. It is called for each match with the match, then each group, then the index, the whole string, and (if there are named groups) a groups object:
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const note = "Tuition 400, books 85.5, lab 45";
console.log(note.replace(/\d+(?:\.\d+)?/g, (amount) => usd.format(Number(amount))));
const template = "Dear {name}, you owe {balance}.";
const data = { name: "Srihitha", balance: "$85.00" };
console.log(template.replace(/\{(\w+)\}/g, (match, key) => data[key] ?? match));Tuition $400.00, books $85.50, lab $45.00
Dear Srihitha, you owe $85.00.The second example is a tiny template engine: each {key} is replaced by the matching value, and unknown keys are left as they were.
split with a Regex
console.log("Navika, Srihitha;Advitha | Zoe".split(/\s*[,;|]\s*/));
console.log(" many spaces here ".trim().split(/\s+/));
console.log("2026-01-05T10:30".split(/[-T:]/));
console.log("a1b2c3".split(/(\d)/));['Navika', 'Srihitha', 'Advitha', 'Zoe']
['many', 'spaces', 'here']
['2026', '01', '05', '10', '30']
['a', '1', 'b', '2', 'c', '3', '']If the pattern contains a capture group, the captured separators are included in the result, as the last line shows.
RegExp.escape (ES2025)
When part of a pattern comes from a user (a search box, a filter), its special characters must be escaped, or they change the pattern's meaning. A search for "$20 (late)" would otherwise treat $, ( and ) as regex syntax. RegExp.escape, added in ES2025, escapes everything that needs it:
const query = "$20 (late)";
console.log(RegExp.escape(query));
const safe = new RegExp(RegExp.escape(query), "i");
console.log(safe.test("Fee: $20 (LATE) applied"));
try {
new RegExp("(late", "i");
} catch (err) {
console.log(err.name);
}\$20\x20\(late\)
true
SyntaxErrorThe escaped form looks strange (\$ is a literal dollar sign, and \x20 is a space, written as a hex code so the result is safe in every position, including inside v-flag classes), but it matches the original text literally. Without escaping, an unbalanced parenthesis typed by a user would throw a SyntaxError. RegExp.escape runs in Node.js 26 and current Chrome, Edge, Firefox and Safari (checked November 2026).
Honest Limits of Regex Validation
Regular expressions check format, not truth. Common patterns have real limits:
| Pattern for | What it can check | What it can't |
|---|---|---|
Something @ something . something | That the address exists or accepts mail. Fully correct email regexes are enormous; a simple check plus a confirmation email is the real-world answer. | |
| US phone | 10 digits in common layouts | That the number is in service; international formats |
| ZIP code | 5 digits, optional -4 | That the ZIP exists |
| Dates | MM/DD/YYYY shape | That February 30 is invalid (use a date library or Temporal) |
| Names | Letters, spaces, hyphens | Every real name: names can contain apostrophes, accents, one letter, or many words |
const SIMPLE_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
for (const e of ["navika@example.com", "advitha@school.edu", "not an email", "a@b.c", "typo@gmial.com"]) {
console.log(e.padEnd(20), SIMPLE_EMAIL.test(e));
}navika@example.com true
advitha@school.edu true
not an email false
a@b.c true
typo@gmial.com trueThe simple pattern catches obvious mistakes, which is its job, and accepts typo@gmial.com, which no pattern can catch. For forms in the browser, <input type="email"> provides this level of checking for free (see the forms lesson).
In Practice
The Fee Tracker normalizes US phone numbers and ZIP codes from a form, extracting the parts with named groups and rebuilding them in one standard format:
const PHONE = /^\s*(?:\+?1[\s.-]?)?\(?(?<area>\d{3})\)?[\s.-]?(?<prefix>\d{3})[\s.-]?(?<line>\d{4})\s*$/;
const ZIP = /^\s*(?<zip>\d{5})(?:-?(?<plus4>\d{4}))?\s*$/;
function normalizePhone(input) {
const g = input.match(PHONE)?.groups;
return g ? `(${g.area}) ${g.prefix}-${g.line}` : null;
}
function normalizeZip(input) {
const g = input.match(ZIP)?.groups;
return g ? (g.plus4 ? `${g.zip}-${g.plus4}` : g.zip) : null;
}
for (const p of ["214.555.0100", "+1 415 555 0199", "(972)5550123", "555-0100"]) {
console.log(p.padEnd(16), normalizePhone(p));
}
for (const z of [" 75201 ", "941031234", "7520"]) {
console.log(z.padEnd(16), normalizeZip(z));
}214.555.0100 (214) 555-0100
+1 415 555 0199 (415) 555-0199
(972)5550123 (972) 555-0123
555-0100 null
75201 75201
941031234 94103-1234
7520 nullThis is also the checkpoint for the regular expressions chapter: validate and normalize a US phone number and ZIP code.
Common Mistakes
Using g with test or exec across strings. lastIndex carries over. Drop the g, or reset re.lastIndex = 0.
Expecting groups from match with g. Use matchAll.
Not handling null from match. Use ?. or ?? [].
Building patterns from raw user input. Escape it with RegExp.escape.
Practice
Challenge: Write highlight(text, term) that wraps every case-insensitive occurrence of term in **...**, keeping the original capitalization, and works even when term contains special characters like $ or (.
Show solution
function highlight(text, term) {
const re = new RegExp(RegExp.escape(term), "gi");
return text.replace(re, (match) => `**${match}**`);
}
console.log(highlight("Late fee applied. LATE notice sent.", "late"));
console.log(highlight("Charge $20 (late) and $20 (early)", "$20 (late)"));**Late** fee applied. **LATE** notice sent.
Charge **$20 (late)** and $20 (early)Key Takeaways
| Task | Code |
|---|---|
| Validate | /^\d{5}$/.test(zip) |
| All matches with groups | for (const m of str.matchAll(/.../g)) |
| Reformat | str.replace(/(\d{3})(\d{4})/, "$1-$2") |
| Computed replacement | str.replace(/\d+/g, (n) => n * 2) |
| Split on several separators | str.split(/\s*[,;]\s*/) |
| Safe dynamic pattern | new RegExp(RegExp.escape(term), "i") |
Was this tutorial helpful?