Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026
The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.
Get All Results with Capturing Groups
When working with regular expressions that use capturing groups, you may need to get all matches from a string.
Getting One Result
const text = 'hello1 bla bla hello2'
const regex = /hello\d/
text.match(regex)
/*
[ 'hello1', index: 0, input: 'hello1 bla bla hello2', groups: undefined ]
*/
Getting Multiple Results
Getting multiple results from a regex can be done using the g flag and it’s automatic, but now the result of match() is different, just the matched result:
const text = 'hello1 bla bla hello2'
const regex = /hello\d/g
console.log(text.match(regex))
//[ 'hello1', 'hello2' ]
Using matchAll()
Using matchAll() (an ES2020 feature) you can get a more detailed result set.
That returns an iterator object, so you need to use a loop to go through the results:
for (let match of text.matchAll(regex)) {
console.log(match)
}
/*
[ 'hello1', index: 0, input: 'hello1 bla bla hello2', groups: undefined ]
[ 'hello2', index: 15, input: 'hello1 bla bla hello2', groups: undefined ]
*/
Named Capturing Groups
Say you have a text containing dates like this:
const text = '2015-01-02 2022-02-04 2040-12-02'
and you have a regex to match that date pattern:
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g
This uses named capturing groups.
Using text.match(regex) now will not give you any information about the groups:
text.match(regex)
// [ '2015-01-02', '2022-02-04', '2040-12-02' ]
but you can get this information using text.matchAll(regex):
for (let match of text.matchAll(regex)) {
console.log(match)
}
/*
[ '2015-01-02', '2015', '01', '02', index: 0, input: '2015-01-02 2022-02-04 2040-12-02', groups: { year: '2015', month: '01', day: '02' } ]
[ '2022-02-04', '2022', '02', '04', index: 11, input: '2015-01-02 2022-02-04 2040-12-02', groups: { year: '2022', month: '02', day: '04' } ]
[ '2040-12-02', '2040', '12', '02', index: 22, input: '2015-01-02 2022-02-04 2040-12-02', groups: { year: '2040', month: '12', day: '02' } ]
*/
So you could extract the year information like this:
for (let match of text.matchAll(regex)) {
console.log(match.groups.year)
}
/*
'2015'
'2022'
'2040'
*/
Capture URL Without Query String
If you need to capture a URL without query parameters (for both http and https links), here’s the regex:
const regex = /^(http[^?#]+).*/gm
Example:
const regex = /^(http[^?#]+).*/gm
const result = regex.exec("https://test.com?test=2")
console.log(result)
/*
[ 'https://test.com?test=2',
'https://test.com',
index: 0,
input: 'https://test.com?test=2',
groups: undefined ]
*/
The captured group (result[1]) contains the URL without the query string.