[我正在尝试一种方法,以将我所有的第1组匹配项放入一个数组中,而不使用带有matchAll()
的循环。
这是我到目前为止的内容,但只产生第一个匹配项:
let str = "123ABC, 123ABC"
let results = str.matchAll(/123(ABC)/gi);
let [group1] = results;
alert(group1[1]);
如何将matchAll
的结果分成一个数组?又名:
// ABC, ABC
您可以使用Array.from
将结果转换为数组并一次性执行映射:
const matches = Array.from(results, match => match[1])
如果只需要字符串的abc
部分,则不需要使用matchAll
方法。只需使用match
方法使用positive lookbehind正则表达式即可轻松获得所需的结果。
let str = "123ABC, 123ABC"
let results = str.match(/(?<=123)ABC/gi);
console.log(results)
// ["ABC","ABC"]
这里是有关这些类型的正则表达式的更多信息Lookahead and lookbehind