Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 38 ยท Getting Started

Regex in JavaScript: The Basics

Use regular expressions in JavaScript and Node.js. Create RegExp objects with literals and the constructor, and use test, exec, match, matchAll, replace, replaceAll, search and split.

JavaScript has regular expressions built in, so you can start using them without installing anything. This lesson shows the two ways to create a regex and the eight methods you will use every day. Everything you learn here carries over to the rest of the course.

Creating a regex

The usual way is a regex literal: a pattern between two slashes, optionally followed by flags.

JavaScript
const re = /colou?r/i;

The second way is the RegExp constructor, which takes the pattern as a string. Use it when the pattern is built at run time.

Node.js Literal and constructor

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.

In a string passed to new RegExp, every backslash of the pattern must be written twice: '\\d', not '\d'. In a literal you write it once: /\d/. Forgetting this is the most common constructor bug. String.raw helps because it keeps backslashes as they are.

test: yes or no

regex.test(string) returns true if the pattern matches anywhere in the string.

Node.js test

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.

exec and match: get the match

regex.exec(string) returns an array describing the first match, or null. Element 0 is the matched text; the array also has index (where it was found) and input.

string.match(regex) works like exec when the regex has no g flag. With g it returns an array of all matched strings (no extra details), or null if there are none.

Node.js exec and match

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.

matchAll: every match with details

string.matchAll(regex) returns an iterator of full match objects (with index and groups) for every match. The regex must have the g flag, or it throws a TypeError.

Node.js matchAll

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.

replace and replaceAll

string.replace(regex, replacement) swaps the first match (or every match with g). replaceAll requires either a string or a regex with g. The replacement can be a string with special tokens ($& is the whole match) or a function.

Node.js 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.

search and split

string.search(regex) returns the index of the first match, or -1. string.split(regex) cuts the string wherever the pattern matches.

Node.js search and split

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.

Which method when?

flowchart TD
  Q["What do you need?"] --> A["A yes/no answer"]
  Q --> B["The matched text"]
  Q --> C["Every match with details"]
  Q --> D["Change the text"]
  Q --> E["Cut the text apart"]
  A --> A1["re.test(s)"]
  B --> B1["s.match(re) or re.exec(s)"]
  C --> C1["s.matchAll(re) with g"]
  D --> D1["s.replace(re, x) / replaceAll"]
  E --> E1["s.split(re)"]

Pick the method by the result you want.

The lastIndex trap

A regex with the g (or y) flag remembers where it stopped in a property called lastIndex. Calling test or exec again continues from there. That is useful for loops, but it surprises people who reuse one global regex.

Node.js lastIndex surprise

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.

Use g with match, matchAll, replace and split-like loops. For a plain yes/no check with test, leave g off.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call returns an array of all matched strings?

    With the g flag, match returns every matched string. Without it, match returns details of the first match only.
  2. 2. Why does new RegExp('\\d+') need two backslashes in the source?

    The string literal consumes one level of escaping, so '\d+' becomes the pattern \d+.
  3. 3. What happens if you pass a regex without g to matchAll?

    matchAll requires the g flag so that it can iterate over all matches.
  4. 4. What does 'abc'.search(/\d/) return?

    search returns the index of the first match, or -1 when there is none.

Summary

  • Create regexes with literals (/x/flags) or new RegExp('x', 'flags'); double backslashes in strings.
  • test answers yes/no, exec and match return the match, matchAll returns all matches with details.
  • replace, replaceAll, search and split all accept regexes.
  • Global regexes keep lastIndex; avoid g with test unless you want the state.

Next: Regex Flavors and Testing Tools