RegExp Methods

Updated · 9 min read
mediumES2026javascriptregexreplacematchallsecurity

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 with g, an array of all matched strings (or null).
  • str.matchAll(re): every match with its groups (needs g); loop with for...of.
  • str.replace(re, replacement) and replaceAll: 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

MethodBelongs toReturns
re.test(str)RegExptrue or false
re.exec(str)RegExpOne match array with groups, or null; with g/y, the next match from lastIndex
str.match(re)StringWithout g: one match array with groups, or null. With g: array of matched strings, or null
str.matchAll(re)StringAn iterator of match arrays with groups (re must have g)
str.search(re)StringIndex of the first match, or -1
str.replace(re, rep)StringNew string; replaces the first match, or all with g
str.replaceAll(re, rep)StringNew string; replaces all (re must have g)
str.split(re, limit)StringArray of the pieces between matches
RegExp.escape(str)RegExp (static)The string with every special character escaped (ES2025)

test: Does It Match?

test.js▶ Try it
const ZIP = /^\d{5}(?:-\d{4})?$/;
console.log(ZIP.test("75201"), ZIP.test("7520"), ZIP.test("94103-1234"));
Output
true false true

test 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:

last-index.js▶ Try it
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"));
Output
true
5
true
false

Explanation: 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

match.js▶ Try it
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}`);
}
Output
Navika paid $120 | Navika 120
['$120', '$45']
null
Navika: $120 at index 0
Advitha: $45 at index 27

Explanation:

  • Without g, match returns the first match with its groups and index.
  • With g, it returns only the matched strings, and null when nothing matches (not an empty array).
  • matchAll returns every match with groups and index. Its regex must have g (it throws a TypeError otherwise). 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

PatternInserts
$&The whole match
$1, $2...A numbered group
$<name>A named group
$` / $'The text before / after the match
$$A literal $
replace.js▶ Try it
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"));
Output
214-555.0100
214-555-0100
214-555-0100
(214) 555-0100
01/05/2026
Total $120.00

replace 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:

replace-fn.js▶ Try it
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));
Output
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

split.js▶ Try it
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)/));
Output
['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:

escape.js▶ Try 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);
}
Output
\$20\x20\(late\)
true
SyntaxError

The 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 forWhat it can checkWhat it can't
EmailSomething @ something . somethingThat 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 phone10 digits in common layoutsThat the number is in service; international formats
ZIP code5 digits, optional -4That the ZIP exists
DatesMM/DD/YYYY shapeThat February 30 is invalid (use a date library or Temporal)
NamesLetters, spaces, hyphensEvery real name: names can contain apostrophes, accents, one letter, or many words
email.js▶ Try it
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));
}
Output
navika@example.com   true
advitha@school.edu   true
not an email         false
a@b.c                true
typo@gmial.com       true

The 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:

normalize.js▶ Try it
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));
}
Output
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             null

This 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
highlight.js▶ Try it
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)"));
Output
**Late** fee applied. **LATE** notice sent.
Charge **$20 (late)** and $20 (early)

Quick check: RegExp methods

3 questions
1Which method returns every match together with its groups?
2What does "a.b.c".replace(".", "-") return?
3Why use RegExp.escape on a search term before new RegExp?

Key Takeaways

TaskCode
Validate/^\d{5}$/.test(zip)
All matches with groupsfor (const m of str.matchAll(/.../g))
Reformatstr.replace(/(\d{3})(\d{4})/, "$1-$2")
Computed replacementstr.replace(/\d+/g, (n) => n * 2)
Split on several separatorsstr.split(/\s*[,;]\s*/)
Safe dynamic patternnew RegExp(RegExp.escape(term), "i")

Was this tutorial helpful?

Lesson 66 of 139