Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Regex in Languages and Tools

Regex in JavaScript: The Complete API

A complete tour of regular expressions in JavaScript: RegExp objects, test, exec, String match, matchAll, search, replace, split, named groups, lastIndex, and common pitfalls.

JavaScript has regular expressions built into the language: literals like /ab+c/i, a RegExp class, and five string methods that accept patterns. Because they are used in browsers, servers (Node.js, Deno, Bun) and tools, JavaScript's flavor is probably the one you meet most often. This lesson is a map of the whole API, with the rules about what each method returns.

Creating a regex

A literal is compiled when the script loads and is best for fixed patterns. The constructor builds a pattern from a string at runtime, which means backslashes must be doubled in the string and user text must be escaped.

Node.js Literals, constructor and escaping

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The methods at a glance

Method Returns Notes
re.test(str) true or false Fast yes/no; stateful with g or y
re.exec(str) Match array or null One match at a time with g or y; has index, input, groups
str.match(re) Without g: like exec. With g: array of strings or null
str.matchAll(re) Iterator of match arrays Requires g
str.search(re) Index of first match or -1 Ignores g and lastIndex
str.replace(re, repl) New string See replace recipes
str.replaceAll(re, repl) New string Requires g
str.split(re, limit) Array of strings See splitting
Node.js Each method on the same text

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Reading a match object

For exec, match (without g) and each item of matchAll:

  • m[0] is the whole match; m[1], m[2]... are the numbered groups (undefined if the group did not take part).
  • m.index is where it starts; m.input is the original string.
  • m.groups is an object with named groups, or undefined if the pattern has none. It has a null prototype, so m.groups.toString is not inherited.
  • With the d flag, m.indices holds the positions (see sticky matching and indices).

Static features and symbols

Since regexes are objects, you can inspect and extend them:

Node.js Properties, named groups and Symbol.replace

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The u and y flags together with s in that first example are only to show that all can combine; real patterns rarely need them all. Note that u and v are mutually exclusive.

Rules of thumb for choosing a method

  • Just need yes or no: test.
  • Need the first match with groups: match (no g) or exec.
  • Need every match with groups and positions: matchAll.
  • Need every matched string only: match with g.
  • Need a position: search (or m.index).
  • Need to transform text: replace / replaceAll with a function.
  • Need to cut text into pieces: split.

Common pitfalls

  1. Reusing a g or y regex with test/exec: lastIndex carries over. Reset it or create new regexes.
  2. Forgetting g with replace: only the first match changes.
  3. match with g returns null, not []: guard with ?? [].
  4. Doubling backslashes: in new RegExp("\\d") the string needs two; in a literal /\d/ it needs one.
  5. Greedy dot over several tags or quotes: use a negated class or a lazy quantifier.
  6. Case folding and Unicode: add u or v when text is not ASCII.
  7. Catastrophic patterns on user input: see ReDoS.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method requires the g flag when given a regex?

    matchAll throws a TypeError for a regex without g. replaceAll has the same rule.
  2. 2. What does str.match(/x/g) return when there is no match?

    match returns null on failure, so use a fallback such as ?? [] before iterating.
  3. 3. How do you write the digit class in new RegExp from a string?

    A backslash in a string literal starts an escape, so the regex backslash must be doubled to reach the engine as one backslash.
  4. 4. What does m.groups contain?

    groups is an object keyed by the group names; indices are available separately with the d flag.

Summary

  • Literals are for fixed patterns; new RegExp is for runtime patterns (double backslashes, escape user text).
  • test answers yes/no, exec and match return match objects, matchAll iterates all matches, replace and split transform strings.
  • A match is an array with index, input and groups.
  • g and y regexes are stateful through lastIndex.
  • Choose the method by the question you are asking, and guard against null.

Next: Regex in Other Languages