0

In this example https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll

Why

const array = [...str.matchAll(regexp)];

instead of just

const array = str.matchAll(regexp);
user310291
  • 36,946
  • 82
  • 271
  • 487

2 Answers2

3

.matchAll returns an iterator. To create an array from the iterator, spreading the iterator into an array is one of the most concise ways to do it.

If you need an array, this is true for any iterator, not just matchAll.

But you don't necessarily need to create an array if you just need to iterate over an iterator. You can also use for..of to iterate without transforming into an array first, for example:

for (const match of str.matchAll(regexp)) {
  // do something with match
}

If you don't turn the iterator into an array first, and use the code in the linked example, logging the plain result won't be very informative:

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const iter = str.matchAll(regexp);
console.log(iter);

In the console, all you see is a RegExpStringIterator object without properties.

If you're wondering why matchAll returns an iterator instead of an array, see here - in short, it allows for performance optimizations in the (somewhat unusual) case that one might want to bail out of iterating over the string before retrieving all the possible matches.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

you can use match instead of matchAll it returns array :

let str = "abcd efgh";
let regex = /([a-z]+)/gi;
let arr = str.match(regex);

arr.forEach((el) => console.log(el));

output :

abcd
efgh
aziz k'h
  • 775
  • 6
  • 11