Sub topic 11
Strings and Regular Expressions: match, matchAll, search
Earlier chapters covered indexOf and includes, which find fixed text. This chapter covers the three string methods that take a regular expression and return information about what matched: match, matchAll, and search. Replacing matched text was covered in the replace chapter, so this one is about reading matches only.
This chapter assumes you can already:
- Write basic regular expressions with character classes (
\d,\w), quantifiers (+,*,{n}), and capture groups( ). - Use arrays,
for...ofloops, and destructuring. - Run code in Node.js 16 or later, or in a current browser console.
The Three Methods at a Glance
Each method answers a different question about a string.
| Method | Question it answers | Returns on success | Returns on failure |
|---|---|---|---|
| `search(re)` | Where is the first match? | Index (number) | `-1` |
| `match(re)` without `g` | What is the first match, and what did its groups capture? | Match array with `index`, `input`, `groups` | `null` |
| `match(re)` with `g` | What text did every match produce? | Array of matched strings | `null` |
| `matchAll(re)` (requires `g`) | What are all the matches, with groups and positions? | Iterator of match arrays | Empty iterator |
The g flag changes what match returns. Most bugs with these methods come from that one difference.
search: The Position of the First Match
search works like indexOf, except it takes a pattern. It returns the index where the first match starts, or -1.
const log = "id=1 id=22 id=333";
console.log(log.search(/=/)); // 2
console.log(log.search(/\d{3}/)); // 14
console.log(log.search(/x/)); // -1
console.log(log.search(/=/g)); // 2 (the g flag is ignored)search always starts at index 0 and ignores both the g flag and the regex's lastIndex. If you need "the next match after position n", search the slice str.slice(n) and add n to the result, or use matchAll.
match Without the g Flag: One Detailed Result
Without g, match returns the first match as an array, with extra properties attached:
- Index
0is the full matched text. - Indexes
1,2, and so on hold capture groups. A group that did not take part in the match isundefined. indexis where the match starts.inputis the original string.groupsis an object of named groups, orundefinedif the pattern has none.
const m = "Due 2026-11-25".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(m[0]); // 2026-11-25
console.log(m[1]); // 2026
console.log(m[3]); // 25
console.log(m.index); // 4
console.log(m.input); // Due 2026-11-25
console.log(m.groups); // undefined
const named = "Due 2026-11-25".match(/(?<year>\d{4})-(?<month>\d{2})/);
const { year, month } = named.groups;
console.log(year, month); // 2026 11Named groups ((?<name>...)) make code easier to read than numeric indexes, and they keep working when you add a new group earlier in the pattern.
Handling null
When nothing matches, match returns null, not an empty array. Destructuring or indexing the result directly throws:
const text = "no date here";
const result = text.match(/(?<year>\d{4})/);
// result.groups.year would throw: Cannot read properties of null
const year = result?.groups.year ?? "unknown";
console.log(year); // unknownmatch With the g Flag: Every Matched String
With g, match returns a plain array of every full match. It drops capture groups, index, and input.
const log = "id=1 id=22 id=333";
console.log(log.match(/id=(\d+)/g)); // ["id=1", "id=22", "id=333"]
console.log(log.match(/\d+/g)); // ["1", "22", "333"]
console.log(log.match(/x/g)); // null, not []
const count = (log.match(/id=/g) ?? []).length;
console.log(count); // 3The first line is a common surprise. The pattern has a group around the digits, but the result only contains full matches. If you want the group values from every match, use matchAll.
matchAll: Every Match With Full Detail
matchAll returns an iterator. Each item it yields has the same shape as a non-global match result: groups, index, input, and groups.
const log = "id=1 id=22 id=333";
for (const m of log.matchAll(/id=(\d+)/g)) {
console.log(m[1], m.index); // 1 0, then 22 5, then 333 11
}
const ids = Array.from(log.matchAll(/id=(\d+)/g), (m) => Number(m[1]));
console.log(ids); // [1, 22, 333]
const pairs = [..."a=1;b=2".matchAll(/(?<key>\w+)=(?<val>\w+)/g)]
.map((m) => [m.groups.key, m.groups.val]);
console.log(Object.fromEntries(pairs)); // { a: '1', b: '2' }Array.from with a mapping function, or spread followed by map, is the usual way to turn the iterator into data.
matchAll Requires the g Flag
Passing a regex without g throws instead of quietly returning one match:
try {
"abc".matchAll(/a/);
} catch (e) {
console.log(e.name); // TypeError
}This is deliberate. A non-global regex can only ever produce one match, so the call is almost certainly a mistake.
The Iterator Is Single-Use
An iterator is consumed as you read it. A second pass gets nothing:
const it = "aaa".matchAll(/a/g);
console.log([...it].length); // 3
console.log([...it].length); // 0If you need the matches more than once, store them in an array first. The upside of laziness is that a loop can break early without processing the rest of a long string.
matchAll Does Not Disturb lastIndex
A global regex object has a lastIndex property that exec and test update. Before matchAll existed, people looped with re.exec(str) and had to manage lastIndex by hand. matchAll works on an internal copy of the regex, so the original object's lastIndex stays the same:
const re = /\d/g;
for (const m of "1 2 3".matchAll(re)) {
// process m
}
console.log(re.lastIndex); // 0
console.log(re.test("5")); // true
console.log(re.test("5")); // false (lastIndex moved past the match)The test lines show the problem matchAll avoids: reusing a global regex with test or exec gives different results on identical input.
Gotchas
Strings Are Converted to Regular Expressions
When you pass a string, all three methods turn it into a regex. Special characters stop being literal:
console.log("price: $5".search("$")); // 9 ($ matches end of string)
console.log("price: $5".indexOf("$")); // 7
console.log("a.b".search(".")); // 0 (. matches any character)
console.log("a+b".match("+")); // throws SyntaxError: nothing to repeatFor literal text, use indexOf or includes, or escape the special characters before building a RegExp.
Empty Matches
Patterns that can match zero characters produce empty matches at every position:
console.log("abc".match(/x*/g)); // ["", "", "", ""]
console.log([..."abc".matchAll(/x*/g)].map((m) => m.index)); // [0, 1, 2, 3]The engine moves forward one position after an empty match, so these calls finish, but the results are rarely what you meant. Use + instead of * when you want at least one character.
Getting Group Positions With the d Flag
m.index gives only the start of the whole match. The d flag adds an indices array with [start, end] pairs for every group:
const m = "key=value".match(/(?<k>\w+)=(?<v>\w+)/d);
console.log(m.indices[0]); // [0, 9]
console.log(m.indices[1]); // [0, 3]
console.log(m.indices.groups.v); // [4, 9]This is useful for highlighting matched parts in an editor or for error messages that point at a column. Engines skip computing indices unless you ask for them, so only add d where you need it.
Unicode Patterns
Without the u (or v) flag, . matches one UTF-16 code unit, so an emoji counts as two characters. The Unicode chapter covers this in detail. Add u when the input may contain characters outside the Basic Multilingual Plane:
console.log("😀".match(/^.$/)); // null
console.log("😀".match(/^.$/u)); // ["😀"]Exercise
You run const tags = post.match(/#(\w+)/g); const names = tags.map((t) => t.slice(1)); on many posts. It crashes on some posts, and a colleague suggests using the capture group instead of slice. Rewrite it with matchAll so it uses the group and never crashes.
Show answer
Use const names = Array.from(post.matchAll(/#(\w+)/g), (m) => m[1]);. The original crashes because match with g returns null when a post has no hashtags. It also cannot use the group, because global match discards capture groups. matchAll yields an empty iterator when nothing matches, so names becomes [], and each item keeps m[1].
Exercise
What do these lines print, and why? console.log("1+1=2".search("+")); and console.log("v1.2".search("."));
Show answer
The first line throws a SyntaxError ("nothing to repeat"), because the string "+" becomes the regex /+/, which is invalid. The second prints 0, because "." becomes /./, which matches any character, so it matches "v" at index 0. To find the literal characters, use "1+1=2".indexOf("+") (1) and "v1.2".indexOf(".") (2).
Exercise
Given const s = "x=10, y=20";, write one expression that produces the array [{ name: "x", at: 0 }, { name: "y", at: 6 }].
Show answer
[...s.matchAll(/(?<name>\w+)=\d+/g)].map((m) => ({ name: m.groups.name, at: m.index })). matchAll gives each match's named groups and its starting index. "x=10" starts at 0, and "y=20" starts at 6 because "x=10, " is six characters long.