Emmanuel Akinfulubi

JavaScriptString

match() with and without the g flag in JavaScript

Intermediate · 3 min read

Pulling numbers out of text is a very common job: the order number from a message, the prices from a receipt, the year from a date. JavaScript's match method does it with a pattern. But match has a twist: one small letter, the g flag, changes what it gives back completely.

In this tutorial you will pull every number out of 'Order 42 shipped on 2025-04-09', then pull just the first number together with its position. You will see why you can't have both from one match call, and how to stay safe when nothing matches. You should know what an array is and that characters in a string are numbered from 0.

The pattern we will use

A regular expression, or regex, is a pattern for text, written between slashes. This exercise uses one:

Pattern

/[0-9]+/

[0-9] means "one digit". + means "one or more of the thing before". Together: a run of digits, like 42 or 2025.

What the g flag does

A letter after the closing slash is a flag. The g flag means global: keep going after the first match and find all of them. match gives a different kind of answer depending on whether the flag is there:

  • Without g: details about the first match only: the text, where it was, and more.
  • With g: a plain list of every matched piece of text, and nothing else.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

11 match, with and without the g flag

fair

Pull every number out of a line of text, then pull just the first one and its position. The g flag decides which of those you can have.

Stuck? Three hints, smallest first
  1. 1. Without g, match returns one match with index, input and groups attached.
  2. 2. With g, it returns a plain array of matched strings and nothing else.
  3. 3. No match returns null, so guard before you read a property off it.

Step 1: the first match, with details

Step 1

const line = 'Order 42 shipped on 2025-04-09';
const one = line.match(/[0-9]+/);
console.log(one[0]);    // '42'
console.log(one.index); // 6
console.log(one.input === line); // true

Without g, match returns an array with extra information attached. Item [0] is the matched text. index is the position where it starts: 'Order ' is six characters, so 42 starts at 6. input is the whole string that was searched.

Step 2: every match, as plain text

Now add the g flag.

Step 2

const line = 'Order 42 shipped on 2025-04-09';
const all = line.match(/[0-9]+/g);
console.log(all);                // [ '42', '2025', '04', '09' ]
console.log(all.index);          // undefined
console.log(Array.isArray(all)); // true

You get all four numbers. The dashes in the date aren't digits, so they split it into three runs. But the positions are gone: all.index is undefined. With g, match returns an ordinary array of strings.

Notice that reading all.index doesn't cause an error. It quietly gives undefined, which makes this an easy bug to miss.

Step 3: when nothing matches

Search for something that isn't there:

Step 3

const line = 'Order 42 shipped on 2025-04-09';
console.log(line.match(/z+/g)); // null

You might expect an empty array, []. You get null, JavaScript's value for "no object at all". Now see what happens if you use it like an array:

JavaScript

const line = 'Order 42 shipped on 2025-04-09';
console.log(line.match(/z+/g).length); // TypeError: Cannot read properties of null (reading 'length')

The program crashes. The usual fix is to swap null for an empty array straight away:

Step 3

const line = 'Order 42 shipped on 2025-04-09';
const found = line.match(/z+/g) || [];
console.log(found.length); // 0

|| means "or": if the left side is null, use the right side instead. Now found is always an array.

Step 4: capture groups

Brackets inside a pattern mark parts you want back separately. They are called capture groups.

Step 4

const parts = 'a1'.match(/([a-z])([0-9])/);
console.log(parts[0]); // 'a1'
console.log(parts[1]); // 'a'
console.log(parts[2]); // '1'

Item [0] is still the whole match. Then each group follows in order: the letter, then the digit.

You can also give a group a name with ?<name> just inside its bracket. Named groups land on .groups:

Step 4

const named = 'a1'.match(/(?<letter>[a-z])/);
console.log(named.groups.letter); // 'a'

Groups only come back like this without g. With g you get the list of whole matches, and the groups are dropped too.

The full solution

Here is the complete answer: one match without g, one with it, the null case, and the groups. Press Run and compare the first two lines of output.

The answer

const line = 'Order 42 shipped on 2025-04-09';

const one = line.match(/[0-9]+/);      // no g: details about the first match
const all = line.match(/[0-9]+/g);     // g: every match, as plain strings

console.log('without g:', one[0], 'at index', one.index);
console.log('with g   :', all);
console.log('no match :', line.match(/z+/g), '<- null, not []');

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('without g, match returns the first hit', one[0], '42');
test('and tells you where it was', one.index, 6);
test('with g, match returns every matched string', all, ['42', '2025', '04', '09']);
test('but drops the positions entirely', all.index, undefined);
test('no match gives null, not an empty array', line.match(/z+/g), null);
test('so default it before using the result', (line.match(/z+/g) || []).length, 0);
test('capture groups follow the whole match', 'a1'.match(/([a-z])([0-9])/).slice(0, 3), ['a1', 'a', '1']);
test('a named group lands in .groups', 'a1'.match(/(?<letter>[a-z])/).groups.letter, 'a');
test('the input string is carried along without g', one.input, line);
test('and the g result is an ordinary array', Array.isArray(all), true);

One method, two return shapes. That is unusual and it catches people: text.match(/x/g).index is undefined, not an error, so a position read off a global match is silently missing rather than obviously wrong.

The null is the other trap. text.match(re).length throws when nothing matched, which is why (text.match(re) || []) appears everywhere. If you want both the positions and all the matches, use matchAll — that is the next exercise.

Common mistakes

  • Reading .index from a g match. It is undefined, not an error, so the bug hides. Leave g off when you need the position.
  • Calling .length or .map on the result without a guard. No match gives null. Write text.match(re) || [].
  • Expecting groups back with g. You only get the whole matches. When you need every match with its groups and position, use matchAll.

Try it yourself

  1. Get every word in 'one two three' with /[a-z]+/g.
  2. Get the first number in 'Room 12, floor 3' and its position.
  3. Write sumNumbers(text) that adds up every number in '3 apples and 4 pears'. Make sure it returns 0 for 'no numbers here'.

Keep practising

Newsletter

New writing, when it lands.

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