Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 156 ยท Built-in Tools

Regular Expressions in Practice

Put regular expressions to work in JavaScript with test, match, matchAll, replace with functions, split, named groups, lookarounds and sensible validation.

In the previous lesson you learned the regex language itself: classes, quantifiers, anchors, groups and flags. A pattern on its own does nothing, though. You need methods that use it โ€” to check input, pull data out of text, clean it up and transform it.

This lesson is about those methods and the real-world patterns built on them. You will learn which method to reach for, how to extract every match with its groups, how to replace text with a function, what lookarounds are for, and how far you should (and shouldn't) go with validation.

Choosing the right method

There are only a handful of methods, split between RegExp and String:

Goal Method Returns
Does it match at all? regex.test(str) true / false
First match with its groups str.match(regex) (no g) a match array or null
All matched strings str.match(regex) (with g) an array of strings or null
All matches with groups str.matchAll(regex) (needs g) an iterator of match arrays
Where is the first match? str.search(regex) an index or -1
Change text str.replace() / str.replaceAll() a new string
Cut text apart str.split(regex) an array

Strings are immutable, so replace() never changes the original โ€” it returns a new string.

test(): yes or no

test() is perfect for if statements and validation:

JavaScript
const hasDigit = /\d/;
if (!hasDigit.test(password)) {
  console.log("Add at least one number.");
}

Remember the warning from the last lesson. A regex with the g flag keeps a lastIndex, and test() starts searching from there:

JS The lastIndex trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

match() and matchAll(): extracting data

Without the g flag, match() returns details about the first match: the full match at [0], each group at [1], [2]โ€ฆ, plus index and groups. With g, it returns just the matched strings and throws away the groups.

When you need every match and its groups, use matchAll(). It requires the g flag (it throws a TypeError without one) and returns an iterator you can loop with for...of or spread into an array.

JS Extracting all prices from text

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Named groups combine nicely with destructuring: const { item, qty } = m.groups. And match() returning null is a classic crash โ€” str.match(re)[0] throws when nothing matches, so use optional chaining or check first.

replace() and replaceAll()

replace(pattern, replacement) with a regex replaces the first match โ€” or all matches if the regex has the g flag. replaceAll() requires a g regex (or a plain string) and always replaces every match.

In the replacement string, special codes insert parts of the match:

Code Inserts
$& the whole match
$1, $2โ€ฆ a numbered group
$<name> a named group
$$ a literal $
JavaScript
"2026-10-14".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");          // "14/10/2026"
"2026-10-14".replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "$<d>.$<m>.$<y>"); // "14.10.2026"
"  too    many   spaces ".trim().replace(/\s+/g, " ");                  // "too many spaces"

Replacing with a function

For anything smarter than rearranging, pass a function as the replacement. It is called once per match with the full match, then each group, and its return value is inserted. This is one of the most useful tricks in JavaScript text processing.

JS Replacing with a function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last example used a lookahead, which is the next topic. Unused parameters are often named _, as in example 3.

split() with a regex

split() accepts a regex, which is handy for messy separators:

JavaScript
"red, green;blue |  yellow".split(/\s*[,;|]\s*/); // ["red", "green", "blue", "yellow"]
"one1two22three".split(/\d+/);                   // ["one", "two", "three"]

Lookarounds

A lookaround checks what comes before or after the current position without including it in the match. There are four:

Syntax Name Means
X(?=Y) lookahead X, if followed by Y
X(?!Y) negative lookahead X, if not followed by Y
(?<=Y)X lookbehind X, if preceded by Y
(?<!Y)X negative lookbehind X, if not preceded by Y
JS Lookarounds

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The thousands trick is clever, but for real number formatting use Intl.NumberFormat โ€” it knows every locale's rules.

Validation patterns

Regexes are great at checking a format. Some patterns worth keeping:

JavaScript
const patterns = {
  zipUS:    /^\d{5}(?:-\d{4})?$/,               // 90210 or 90210-1234
  hexColor: /^#(?:[0-9a-f]{3}){1,2}$/i,         // #fa0 or #ffaa00
  isoDate:  /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/,
  time24:   /^([01]\d|2[0-3]):[0-5]\d$/,
  slug:     /^[a-z0-9]+(?:-[a-z0-9]+)*$/,        // my-first-post
  username: /^[a-z][a-z0-9_]{2,15}$/i,
};

Know when to stop. A regex can check the shape of a value but not whether it is real. isoDate happily accepts February 31. Email addresses are famously impossible to validate fully with a regex โ€” a simple /^[^\s@]+@[^\s@]+\.[^\s@]+$/ catches typos, and the only true test is sending a confirmation email. In forms, the browser's own validation (type="email", pattern) and server-side checks should always back up your regex.

A quick tester makes it easy to experiment with your own inputs:

Live pattern tester

Escaping user input

If you build a regex from user input with new RegExp(input), characters like . or ( in the input become special โ€” and an unbalanced ( throws an error. Escape them first:

JavaScript
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(escapeRegExp("price (USD)"), "i");

Newer browsers include a built-in RegExp.escape() (added to the language in 2025). Feature-detect it with typeof RegExp.escape === "function" and keep the helper as a fallback.

Mind performance with nested quantifiers. Patterns like /(a+)+$/ can take an exponentially long time on certain inputs ("catastrophic backtracking"), freezing the page. Keep patterns simple and specific, prefer negated classes like [^"]* over .*, and never run complex user-supplied patterns on a server without limits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You need every match of a pattern together with its capture groups. Which method fits best?

    match() with g returns only the matched strings. matchAll() gives a full match object, including groups, for each match.
  2. 2. What does "a-b-c".replace(/-/, "+") return?

    Without the g flag, replace() only changes the first match.
  3. 3. In a replacer function (match, p1) => ..., what is p1?

    The function receives the full match first, then each capture group in order, then the index and the whole string.
  4. 4. With the g flag, what does /\d+(?=px)/g match in "12px 5em 30px"?

    The lookahead requires "px" after the digits but doesn't include it in the match. "5" is followed by "em", so it is skipped.
  5. 5. Why might /cat/g.test() return false on a string containing "cat"?

    Global and sticky regexes remember lastIndex. Reusing one with test() continues from where the last match ended.

Summary

  • test() answers yes/no; match() gives the first match with groups (or all strings with g); matchAll() gives every match with groups.
  • replace() changes the first match unless the regex has g; replaceAll() changes every match. Use $1, $<name> and $& in replacement strings.
  • A replacer function receives the match and its groups and returns the new text โ€” ideal for transformations.
  • Lookarounds ((?=), (?!), (?<=), (?<!)) add conditions without consuming text.
  • Regexes check format, not meaning. Escape user input before building a pattern, and avoid nested quantifiers.

Next: Iterators and Generators โ€” the protocol behind for...of, and functions that pause.