Emmanuel Akinfulubi

JavaScriptString

Use matchAll to get every regex match in JavaScript

Intermediate · 4 min read

Real text often holds several pieces of data in a row: 'Lagos 21C, Abuja 33C, Kano 38C'. To turn it into something a program can use, you need every match, and for each one you need its parts, the city and the temperature, not just the whole piece of text.

match can't give you both at once. matchAll can. In this tutorial you will turn that line into a list of { city, temp } objects, keep the position of each match, and find the hottest city. You should know what an array and an object are, and have met map. Regular expressions are explained below from the start.

A pattern for one reading

A regular expression, or regex, is a pattern for text, written between slashes. Here is the one this exercise uses, piece by piece:

Pattern

(?<city>[A-Z][a-z]+) (?<temp>[0-9]+)C
  • [A-Z] is one capital letter, and [a-z]+ is one or more lower-case letters. Together they match a name like Lagos.
  • The space matches the space.
  • [0-9]+ is one or more digits, like 21.
  • C matches the letter C.
  • Round brackets mark a capture group, a part you want back on its own. ?<city> gives the group a name, so you can ask for "the city" instead of "group 1".

Iterators

matchAll doesn't return an array. It returns an iterator: an object that hands you items one at a time when you loop over it. You can turn it into an array with the spread syntax, [...it], which collects every item.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

12 matchAll, for every match with its details

fair

Parse 'Lagos 21C, Abuja 33C, Kano 38C' into a list of { city, temp } objects, keeping the position of each match.

Stuck? Three hints, smallest first
  1. 1. matchAll returns an iterator, so spread it or loop over it.
  2. 2. Each item is a full match object, so groups and index are both there.
  3. 3. It requires the g flag and throws without it.

Step 1: write the pattern with the g flag

Step 1

const line = 'Lagos 21C, Abuja 33C, Kano 38C';
const READING = /(?<city>[A-Z][a-z]+) (?<temp>[0-9]+)C/g;

The g after the closing slash is the global flag: find every match, not just the first. matchAll needs it. The name is in capitals as a reminder that it is a fixed value used throughout.

Step 2: get every match

Step 2

const line = 'Lagos 21C, Abuja 33C, Kano 38C';
const READING = /(?<city>[A-Z][a-z]+) (?<temp>[0-9]+)C/g;
const matches = [...line.matchAll(READING)];
console.log(matches.length);    // 3
console.log(matches[0][0]);     // 'Lagos 21C'
console.log(matches[0].groups); // { city: 'Lagos', temp: '21' }
console.log(matches[1].index);  // 11

Each item is a full match object: [0] is the whole match, .groups holds the named parts, and .index is where the match starts. 'Lagos 21C, ' is 11 characters, so Abuja starts at 11. A match call with g would have thrown the groups and positions away.

Node prints .groups with a small extra label in front, [Object: null prototype]. You can ignore it: it is a plain set of names and values.

Step 3: turn matches into objects

Now use map to turn each match into the shape you want.

Step 3

const line = 'Lagos 21C, Abuja 33C, Kano 38C';
const READING = /(?<city>[A-Z][a-z]+) (?<temp>[0-9]+)C/g;
const readings = [...line.matchAll(READING)].map((m) => ({
  city: m.groups.city,
  temp: Number(m.groups.temp),
}));
console.log(readings[0]); // { city: 'Lagos', temp: 21 }
console.log(readings[2]); // { city: 'Kano', temp: 38 }

Anything a regex captures is text, so temp starts as '21'. Number(...) turns it into the number 21, so you can compare and add temperatures. The round brackets around { ... } tell JavaScript the arrow function returns an object, rather than starting a block of code.

Step 4: forget the g flag

What happens without g?

Step 4

const line = 'Lagos 21C, Abuja 33C, Kano 38C';
const withoutG = (() => {
  try {
    return [...line.matchAll(/[0-9]+/)].length;
  } catch (e) {
    return e.constructor.name;
  }
})();
console.log(withoutG); // 'TypeError'

It refuses, with the message String.prototype.matchAll called with a non-global RegExp argument. That is a good thing: a loud error instead of quietly finding just one match. The try { } catch (e) { } runs the code and, if it throws, hands the error to catch. The (() => { ... })() wrapper runs straight away and stores its result in withoutG.

Step 5: no matches, no crash

Step 5

console.log([...'no readings'.matchAll(/z+/g)]); // []
console.log(Array.isArray('x'.matchAll(/x/g)));  // false

When nothing matches you get an empty list, not null as match gives, so there is nothing to guard against. The second line is a reminder that you must spread the iterator before you can use array methods like map or .length.

Step 6: find the hottest city

With real objects, the rest is ordinary array work.

Step 6

const readings = [
  { city: 'Lagos', temp: 21 },
  { city: 'Abuja', temp: 33 },
  { city: 'Kano', temp: 38 },
];
const hottest = readings.reduce((a, b) => (b.temp > a.temp ? b : a));
console.log(hottest.city); // 'Kano'

reduce walks the list, keeping whichever reading is hotter, a or b, at each step. What is left at the end is the hottest.

The full solution

Here is the complete answer: the pattern, the readings printed in a neat column, and the refusal without g. Press Run to see the table.

The answer

const line = 'Lagos 21C, Abuja 33C, Kano 38C';
const READING = /(?<city>[A-Z][a-z]+) (?<temp>[0-9]+)C/g;

const readings = [...line.matchAll(READING)].map((m) => ({
  city: m.groups.city,
  temp: Number(m.groups.temp),
}));

// Without the g flag it refuses, rather than matching once.
const withoutG = (() => {
  try { return [...line.matchAll(/[0-9]+/)].length; } catch (e) { return e.constructor.name; }
})();

for (const r of readings) console.log(r.city.padEnd(6), r.temp + 'C');
console.log('matchAll without g:', withoutG);

Output


      
10 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('every reading is found', readings.length, 3);
test('the first one is parsed properly', readings[0], { city: 'Lagos', temp: 21 });
test('and the last', readings[2], { city: 'Kano', temp: 38 });
test('matchAll keeps the index that match with g throws away', [...line.matchAll(READING)][0].index, 0);
test('the second match knows where it starts', [...line.matchAll(READING)][1].index, 11);
test('matchAll without the g flag throws', withoutG, 'TypeError');
test('the return value is an iterator, not an array', Array.isArray(line.matchAll(READING)), false);
test('so it has to be spread or looped', Array.isArray([...line.matchAll(READING)]), true);
test('no match gives an empty list rather than null', [...line.matchAll(/z+/g)], []);
test('the hottest city', readings.reduce((a, b) => (b.temp > a.temp ? b : a)).city, 'Kano');

matchAll is what match(/x/g) should have been: every match, each one a full object with its groups and its index. Reaching for it should be the default when a pattern has capture groups.

It gives you an iterator rather than an array, which means it can be looped once without building the whole list — and it means .length and .map are not available until you spread it. It also insists on g, throwing instead of silently behaving like match, which is the right call.

Common mistakes

  • Leaving off the g flag. matchAll throws a TypeError. Always write /.../g.
  • Calling .map on the result directly. It is an iterator, not an array. Spread it first: [...text.matchAll(re)].
  • Comparing captured numbers as text. Groups are strings, and '9' > '38' is true. Convert with Number.

Try it yourself

  1. Add a check that the coolest city is Lagos, using reduce the other way round.
  2. Print each city with the position where its reading starts, using m.index.
  3. Parse 'apples=3; pears=5' into [{ name: 'apples', count: 3 }, { name: 'pears', count: 5 }].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.