Find a course

Module 3: Regex in CodeLesson 7 of 1215 min

Regex in JavaScript

Create patterns with literals and the RegExp constructor, choose between test, match, matchAll, replace and split, and avoid the lastIndex trap.

Step 1 of 14Learn

Two ways to write a pattern

JavaScript has regex built into the language. There are two ways to create one:

const a = /\d{3}-\d{4}/g;                   // regex literal
const b = new RegExp("\\d{3}-\\d{4}", "g"); // constructor

The literal is compiled when the script loads, reads cleanly and is the usual choice. The RegExp constructor builds a pattern from a string at run time, which you need when the pattern isn't known in advance, for example when searching for a word the user typed.

The constructor has a notorious trap: double escaping. The pattern is first a JavaScript string, and in string literals the backslash is itself an escape character. The string "\d" is just "d," because \d isn't a recognized string escape. To get the two characters backslash and d into the pattern, the string must contain "\\d". Every backslash in the pattern becomes two in the string. Forgetting this produces patterns that silently match the wrong thing.

When building a pattern from user input, also escape metacharacters in that input. A user searching for "C++" would otherwise create the pattern C++, which is invalid. A common helper replaces each special character with a backslashed version before passing the text to RegExp.

Step 2 of 14Compare

Literal vs. RegExp constructor

Aspect/\d+/gnew RegExp("\\d+", "g")
Pattern known when you write the codeBest choiceWorks, but noisier
Built from a variable or user inputNot possibleRequired (escape the input!)
BackslashesWritten onceDoubled inside the string
FlagsAfter the closing slashSecond argument

Step 3 of 14Practice · Choose one

Which JavaScript expression creates a pattern that matches one or more digits?

Step 4 of 14Learn

The core methods

JavaScript spreads regex features across string and RegExp methods. The ones you'll use constantly:

MethodReturnsUse it to
re.test(str)true or falsecheck whether there is a match
str.match(re) without gfirst match with groups, or nullextract one match and its captures
str.match(re) with garray of all matched strings, or nulllist every match (no groups)
str.matchAll(re)iterator of match objects (needs g)loop over every match with its groups
str.replace(re, x)new stringsubstitute matches
str.split(re)array of piecescut text at each match
str.search(re)index of first match, or −1find a position

Two behaviors cause many bugs. First, match with the g flag drops the groups: it returns only the matched strings. To get every match and its captures, use matchAll:

const text = "a=1, b=22";
for (const m of text.matchAll(/(\w)=(\d+)/g)) {
  console.log(m[1], m[2]); // "a" "1", then "b" "22"
}

Second, split with capturing groups keeps the separators: "a1b2c".split(/(\d)/) gives ["a", "1", "b", "2", "c"]. Use a non-capturing group or no group if you only want the pieces.

Step 5 of 14Practice · Diagram

Which JavaScript method?

You need the year, month and day of every date in a log. Which branch?

Tap the shape that answers the question, then press Check.

Which JavaScript method?Hierarchy diagram: What do you need?, Yes or no, First match + groups, Every match + groups, Change the text, Cut into pieces.What do youneed?Yes or noFirstmatch +groupsEverymatch +groupsChange thetextCut intopieces
What do you need?
Yes or no

re.test(str)

First match + groups

str.match(re) without g, or re.exec(str)

Every match + groups

str.matchAll(re), which needs the g flag

Change the text

str.replace / str.replaceAll

Cut into pieces

str.split(re)

Step 6 of 14Practice · Match the pairs

Match each goal to the JavaScript method that fits best.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Check if an input contains a digit
  2. Loop over every key=value pair with its captured parts
  3. Turn "a, b;c" into ["a", "b", "c"]
  4. Mask every credit card number in a message

Step 7 of 14Learn

The lastIndex trap

A regex with the g (or y) flag is stateful in JavaScript. It has a lastIndex property recording where the last match ended, and test and exec start searching from there. That leads to one of the most confusing bugs in the language:

const hasDigit = /\d/g;
hasDigit.test("a1"); // true  (lastIndex is now 2)
hasDigit.test("b2"); // false (search started at index 2, past the end)
hasDigit.test("b2"); // true  (lastIndex was reset to 0 after the failure)

The same input gives different answers on alternate calls. It typically appears when a global regex is stored in a constant and reused to validate many strings, for example inside a filter over a list.

The fixes are simple:

  • Don't use g with test unless you specifically want to step through matches. For a yes/no check, /\d/ is enough.
  • If you must reuse a global regex, reset re.lastIndex = 0 before each use, or create the regex inside the function.

Methods like str.match, str.replace and str.matchAll handle lastIndex for you, which is one more reason to prefer them for everyday work.

Step 8 of 14Practice · Diagram

Three calls to /\d/g.test()

Which call shows the bug?

Tap the shape that answers the question, then press Check.

Three calls to /\d/g.test()Process diagram: test("a1") → true → test("b2") → false → test("b2") → true.test("a1") → truetest("b2") → falsetest("b2") → true
test("a1") → true

Match ends at index 2, so lastIndex becomes 2.

test("b2") → false

Search starts at index 2, past the end. lastIndex resets to 0.

test("b2") → true

Starts from 0 again.

Step 9 of 14Practice · True or false

Calling .test() twice on the same string with a regex that has the g flag always returns the same result both times.

Step 10 of 14Note

Step 11 of 14Practice · Code challenge

Write hashtags(text) that returns an array of all hashtags in the text without the # sign, in order. A hashtag is # followed by one or more word characters. Use matchAll with a capture group. Return an empty array if there are none.

Runs in a sandbox in your browser.
  • hashtags("Loving #regex and #JavaScript today")
  • hashtags("no tags")
  • hashtags("#a #b2 # c")
  • hashtags("end with #last")

Step 12 of 14Practice · Spot the mistake

A code reviewer flags this function, meant to keep only the strings containing a digit. Tap the line that causes intermittent wrong results.

Step 13 of 14Note

Step 14 of 14Practice · Choose one

What does "2026-03-14".split(/-/) return?