Matching in JavaScript
Choose between test, exec, match, matchAll and search by what each returns, see the g plus lastIndex bug in a validator, and avoid the string-as-pattern traps.
Flags: ignore case, global and multilineCapturing groups and numbering
Matching in JavaScript
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Pick the method by what you need back. test gives true or false, exec gives one match object, match gives the first match or, with g, all the strings, matchAll gives an iterator of full match objects, and search gives an index.
- match without g and exec return the same thing, the whole match then the groups plus index. match with g returns only the matched strings and drops the groups, so use matchAll when you need both.
- A regex literal with g or y is stateful. Keep one in a variable and call test on it repeatedly, and results alternate: [true, false, true, false] for four numeric strings.
- exec in a while loop with a pattern that can match the empty string never advances, because lastIndex stays put. matchAll does not have that problem.
- A string passed to match or search becomes a regex, so 'a.b'.match('.') matches a. Write /\./ for a literal dot, and remember '\d' inside a string is just d.
One engine, five doors
JavaScript gives you five ways to ask the same engine a question, and they look similar enough that people pick one at random and then fight its return value. The fix is to start from what you need back.
I used one string for every example: order 66, order 7, order 1024.
| You need | Use | Returns |
|---|---|---|
| yes or no | regex.test(s) |
true or false |
| the first match with its groups | regex.exec(s) or s.match(regex) |
a match object, or null |
| every matched string | s.match(/.../g) |
array of strings, or null |
| every match with groups and positions | s.matchAll(/.../g) |
an iterator of match objects |
| just the position | s.search(regex) |
index, or -1 |
Writing the regex: literal or constructor
A literal, /\d+/, is parsed once when the script loads and is the usual choice. new RegExp('\\d+') builds the same thing from a string and is for patterns you assemble at runtime. Both printed as /\d+/.
The trap is the string. new RegExp('\d+') printed /d+/, because \d in a normal string literal is just d. It’s a string escape that happens to have no meaning, and it is dropped before the regex ever sees it. On abc 5, the doubled version matched (true) and the single one didn’t (false). Double the backslash, or write String.raw followed by a template string, which keeps backslashes as typed. Interpolation works in a template literal too: new RegExp(`${word} (\\d+)`, 'g') found 66. Be careful when word comes from a user, though. The last lesson in this group covers escaping that safely.
test, exec and match
/\d+/.test(s) // true
/order (\d+)/.exec(s)
// [ 'order 66', '66', index: 0, input: '...', groups: undefined ]
/nope/.exec(s) // null
s.match(/order (\d+)/) // the same array exec returned
s.match(/order (\d+)/g) // [ 'order 66', 'order 7', 'order 1024' ]
'nothing'.match(/\d/g) // null
Without g, match and exec return the same thing: the whole match, then the capture groups, plus index and input. With g, match changes shape. It gives you only the matched strings and throws away the groups and positions. If you want every match and its groups, that is matchAll:
for (const m of s.matchAll(/order (?<n>\d+)/g))
console.log(m[0], '|', m[1], '|', m.index, '|', m.groups.n);
// order 66 | 66 | 0 | 66
// order 7 | 7 | 10 | 7
// order 1024 | 1024 | 19 | 1024
[...s.matchAll(/\d+/g)].map(m => Number(m[0])) // [ 66, 7, 1024 ]
matchAll returns an iterator, so spread it or loop over it. It requires g and throws a TypeError without it, as the flags lesson showed.
The g and lastIndex bug, in the wild
A very common bug is a validator written once at the top of a module:
const isNumber = /^\d+$/g; // the g is the mistake
['12','34','56','78'].map(x => isNumber.test(x))
// [ true, false, true, false ]
const isNumber2 = /^\d+$/;
['12','34','56','78'].map(x => isNumber2.test(x))
// [ true, true, true, true ]
Each successful test on a global regex moves lastIndex to the end of the match, and the next call starts there. That is a search from the end of 12 in 34, which fails and resets to 0. Every second call gives the wrong answer on perfectly good input. Two fixes: drop the g when you only want a boolean, or set lastIndex = 0 before each test. s.match(g) is safer, because it starts from the beginning whatever lastIndex held (I set it to 5 and 'a1 2'.match(/\d/g) still returned both digits). matchAll is not immune: it works on a copy, so it leaves your regex’s lastIndex alone, but the copy starts at the lastIndex it inherits. With lastIndex at 3, matchAll found one digit, not two. A regex literal in a function body creates a fresh object on each call (lit() === lit() was false), so the bug only appears when the regex lives outside the function.
exec in a loop: the empty-match trap
The classic way to walk through matches was a while loop on exec:
const e = /a*/g; // can match the empty string
// calling e.exec('baab') repeatedly returned [ '', index 0, lastIndex 0 ] every time
I capped the loop at six iterations, because an uncapped one never ends: the match is empty, so lastIndex doesn’t move, and the next exec finds the same empty match at the same place. [...'baab'.matchAll(/a*/g)] ran fine and returned ['', 0], ['aa', 1], ['', 3] and ['', 4], because matchAll advances past an empty match on its own. So prefer matchAll for walking all matches.
search, and strings that turn into regexes
s.search(/\d/) returned 6, and s.search(/xyz/) returned -1. It ignores g and lastIndex. With lastIndex set to 10 on a global regex, search still found the digit at 6 and left lastIndex at 10.
Last, match and search accept a string and convert it to a regex. 'a.b'.match('.')[0] gave a, since . is the any-character dot, and 'a.b'.search('.') returned 0. 'a+b'.match('+') threw SyntaxError: ... Nothing to repeat. If you mean literal text, use includes or indexOf, or build an escaped pattern. In the JavaScript roadmap, regular expressions covers the same methods from the language side.
About the video
The embedded video is The Coding Train’s “2.6: Regular Expressions: test() and match() - Programming with Text”, published 18 September 2016 and 16 minutes 50 seconds long. Its chapters are Introduction to regex, Testing regex patterns, Matching with .match(), Global and case flags and Extracting capture groups. The description says it covers the difference between literal strings and regular expressions, and the test() and match() functions. It is part of an NYU course and uses JavaScript. The video is from 2016 and neither its description nor its chapters mention matchAll, so that method, the validator bug and the empty-match trap are my own runs, not the video’s. I couldn’t read a transcript. The two “deeper” links cover the lastIndex bug and match/matchAll in more detail. English per its title and description.
What I did not run
Browser behaviour, since everything here ran on Node 26, and the older RegExp.$1 static properties.
Next
Matching finds things. Replacing with regex uses what you found to rewrite the text.
Check yourself
You only need to know whether a string contains digits. Which method fits, and which flag should you avoid?
/\d/.test(str), which returns a boolean. Avoid g, because a global regex keeps lastIndex between calls and can return false for an input that should match.
What is the difference between s.match(/\d+/g) and [...s.matchAll(/\d+/g)]?
The first returns an array of the matched strings only. The second returns full match objects, each with groups, index and input, so you can read capture groups and positions.
Why does new RegExp('\d+') not match 5?
In a string literal, \d is just d, so the pattern is /d+/. You must double the backslash, new RegExp('\\d+'), or use String.raw to write the pattern as typed.
What does str.search(/x/) return, and what does it ignore?
It returns the index of the first match, or -1. It ignores the g flag and lastIndex, and leaves lastIndex unchanged, so it is safe to use with a shared regex.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.