1

I'm trying to figure out a way to get all my Group 1 matches into an array without using a loop with matchAll().

Here's what I have thus far, but it only yields the first match:

let str = "123ABC, 123ABC"
let results = str.matchAll(/123(ABC)/gi);
let [group1] = results;
alert(group1[1]);

How can I get the results of the matchAll into one single array? Aka:

// ABC, ABC
NaviRetail
  • 39
  • 6

3 Answers3

2

const str = "123ABC, 123ABC"

const results = Array.from(
  str.matchAll(/123(ABC)/gi), 
  ([_, g1]) => g1
)

console.log(results)
kornieff
  • 2,389
  • 19
  • 29
1

If you only need the abc part of the string then you don't need to use matchAll method. You can easily get the results you want simply using the positive lookbehind regex expresion with the match method.

let str = "123ABC, 123ABC"
let results = str.match(/(?<=123)ABC/gi);
console.log(results)
// ["ABC","ABC"]

Here is some more information on these types of regex expressions Lookahead and lookbehind

marshy101
  • 594
  • 7
  • 19
0

You can use Array.from to convert results to array and perform map in one go:

const matches = Array.from(results, match => match[1])
Alex
  • 1,724
  • 13
  • 25