简体   繁体   中英

matchAll Array for Group 1 Regex Matches

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

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

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

您可以使用Array.from将结果转换为数组并一次性执行映射:

 const matches = Array.from(results, match => match[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM