Global match in JavaScript regexes

The match method, invoked with the g modifier, returns all found matches as an array. Let's look at examples.

Example

Let's obtain an array of substrings consisting of the letters 'a':

let str = 'a aa aaa aaaa'; let res = str.match(/a+/g);

As a result, the following will be written to the variable:

['a', 'aa', 'aaa', 'aaaa']

Example

Let's get an array of numbers:

let str = '1 23 456 789'; let res = str.match(/\d+/g);

As a result, the following will be written to the variable:

['1', '23', '456', '789']

Example

Let's get an array of all digits:

let str = '1 23 456 789'; let res = str.match(/\d/g);

As a result, the following will be written to the variable:

['1', '2', '3', '4', '5', '6', '7', '8', '9']

Practical tasks

Given a string:

let str = 'site.ru sss site.com zzz site.net';

Get an array of domain names from this string.

Given a string:

let str = 'a1b c34d x567z';

Find the sum of all numbers in this string.

enru