Regular expressions: test, match and the g flag

A regular expression describes a shape of text, and the methods of a string ask it questions: does this text have the shape, which part matched, and where. The pattern is written as a literal between two slashes, so /\d+/ is one or more digits and it needs no quotes or escapes beyond the ones the pattern itself has.

The lesson keeps to four methods and one flag, because the flag is where the surprises are. A global pattern remembers the position of its last match, so the same call can answer true and then false on the same text. The programs below print that position beside the answer, so the behaviour is visible rather than memorised.

A literal and test

test answers a boolean and stops at the first match. The pattern below is anchored with ^ and $, so it describes the whole string rather than a part of it, and \d is a digit while {3} means exactly three of them. The flag i makes the match case-insensitive.

const threeDigits = /^\d{3}$/; console.log('123:', threeDigits.test('123')); console.log('12:', threeDigits.test('12')); console.log('1234:', threeDigits.test('1234')); console.log('12a:', threeDigits.test('12a')); console.log('case-insensitive:', /hello/i.test('Hello')); console.log('source:', threeDigits.source); console.log('flags:', /hello/i.flags);

node test.js

123: true
12: false
1234: false
12a: false
case-insensitive: true
source: ^\d{3}$
flags: i

Only the first string has the shape, and the three that failed show the three ways a test can fail: too few digits, too many and a letter. The anchors are what make the difference between a test of the whole string and a search inside it, and dropping them would accept 12a as well. source and flags give the pattern back as text, which is what a log line needs.

match

match returns an array of what it found, or null when the text does not have the shape. Without the g flag the first element is the whole match, the following elements are the capture groups and the array carries the position. With g the answer is a plain array of all matches and the groups are lost.

const text = 'order 42, item 7, total 105'; console.log('first:', text.match(/\d+/)[0]); console.log('all:', text.match(/\d+/g).join(', ')); console.log('count:', text.match(/\d+/g).length); const date = '2024-05-17'.match(/(\d{4})-(\d{2})-(\d{2})/); console.log('groups:', date.slice(1).join('/')); console.log('at index:', date.index); console.log('no match:', 'abc'.match(/\d+/));

node match.js

first: 42
all: 42, 7, 105
count: 3
groups: 2024/05/17
at index: 0
no match: null

The first call found forty-two and the global one found all three numbers in the order they appear. The date line is the reason to drop the flag when the groups matter: the array holds the match and then the three parts, and slice(1) takes them without the whole. A null from a failed match is easy to forget, so a program that reads [0] from the answer has to know that the text is there.

The g flag and lastIndex

A global pattern is stateful: test and exec start at lastIndex and update it after a match. On a string that keeps matching, the same call therefore answers true again from further on, and eventually false when the search reaches the end. A fresh string does not reset the position, which is why a global pattern kept in a variable is a bug.

const re = /\d+/g; const text = 'a1 b22'; console.log('one:', re.test(text), 'lastIndex:', re.lastIndex); console.log('two:', re.test(text), 'lastIndex:', re.lastIndex); console.log('other string:', re.test('x7'), 'lastIndex:', re.lastIndex); console.log('other string again:', re.test('x7'), 'lastIndex:', re.lastIndex); console.log('fresh pattern:', /\d+/.test(text), 'lastIndex:', /\d+/.lastIndex);

node lastindex.js

one: true lastIndex: 2
two: true lastIndex: 6
other string: false lastIndex: 0
other string again: true lastIndex: 2
fresh pattern: true lastIndex: 0

The first two calls were true and moved the position to two and then to six. The third call then searched a different string from position six, which is past the end of a two-character string, so it answered false about text that does contain a digit. The fourth call started from zero again and found it, so one function can answer differently on identical input depending on what ran before it. The fix is a pattern without g for a test, or a new literal for each call, which is what the last line does.

exec in a loop

exec returns the same array as match without the flag, and a global pattern advances its position after each call. That combination is the loop that walks every match with its index and its groups. matchAll is the newer form of the same walk and it needs the g flag as well.

const text = 'a1 b22 c333'; const re = /\d+/g; let match = re.exec(text); while (match !== null) { console.log('value:', match[0], 'at', match.index); match = re.exec(text); } console.log('lastIndex after the loop:', re.lastIndex); for (const found of text.matchAll(/\d+/g)) { console.log('matchAll:', found[0], found.index); }

node exec.js

value: 1 at 1
value: 22 at 4
value: 333 at 8
lastIndex after the loop: 0
matchAll: 1 1
matchAll: 22 4
matchAll: 333 8

Each match came with the position it started at, and the loop ended when the pattern reached the end of the string: the failed call is also the one that reset the position to zero, which is the state the next section of a program has to expect. The matchAll loop printed the same values without the variable and without the hidden position, so it is the form to prefer in new code.

Exercises

  1. Drop the anchors from the pattern in test.js and run it again. Which of the four strings pass, and why does the last one now pass?
  2. Test /^\d+$/ against '12 34' and against '1234'. Which one passes, and what does that say about the anchored pattern?
  3. Remove the g flag from the pattern in lastindex.js. Which lines of the output change, and what does lastIndex stay at?
  4. Call match with the pattern /(\d)(\d)/g on '12 34'. How many elements does the answer have, and where are the groups?
  5. Replace the word characters in the pattern of exec.js with /\w+/g. How many matches arrive, and which position does the first one have?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does test return?

    Answer

    A boolean

    test stops at the first match and answers whether there was one.

  2. What does this program print? console.log(/^\d{3}$/.test('1234'));

    Answer

    false

    The anchors describe the whole string, and four digits do not fit a pattern of exactly three.

  3. What does this program print? console.log('a1b22'.match(/\d+/g).length);

    Answer

    2

    The global flag collects every match, and there are two runs of digits.

  4. What does this program print? console.log('abc'.match(/\d+/));

    Answer

    null

    A failed match gives null rather than an empty array, which is why the answer is checked first.

  5. What does the g flag do to match?

    Answer

    It returns all matches and drops the groups

    A global match is a plain array of the matched texts, and the groups belong to the non-global form.

  6. What does this program print? const re = /\d/g; console.log(re.test('a1'), re.lastIndex);

    Answer

    true 2

    The match starts at index one and ends at index two, so the position moves to two.

  7. Why can a global pattern answer false on a string it matched before?

    Answer

    Because lastIndex is still at the end from the previous call

    The position survives between calls, so the next search starts where the last one stopped.

  8. What does this program print? const re = /a/g; console.log(re.test('a'), re.test('a'));

    Answer

    true false

    The first call moves the position past the only a, and the second call starts too late.

  9. What does exec return for a pattern with the g flag?

    Answer

    The next match with its index and groups, and it moves lastIndex

    exec walks the matches one call at a time, which is how the loop with the position works.

  10. Which method is the newer form of the exec loop?

    Answer

    matchAll

    matchAll returns an iterator of the matches with their positions and needs the g flag.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev