matchAll()
方法在将一个字符串与一个正则表达式匹配后,会返回一个结果的迭代器。
示例
// string definition
const sentence = "JavaScript1JavaScript2";
// a pattern having 'JavaScript' followed by a digit
const regex = /JavaScript\d/g;
// finding matches in the string for the given regular expression
let results = sentence.matchAll(regex);
// looping through the iterator
for (result of results) {
console.log(result);
}
// Output:
// ["JavaScript1", index: 0, input: "JavaScript1JavaScript2", groups: undefined]
// ["JavaScript2", index: 11, input: "JavaScript1JavaScript2", groups: undefined]
matchAll() 语法
matchAll()
方法的语法是:
str.matchAll(regexp)
这里,str
是一个字符串。
matchAll() 参数
matchAll()
方法接受单个参数:
- regex - 一个正则表达式对象 (如果非
regex
对象,参数会被隐式转换为regex
)
注意
- 如果
regex
对象没有/g
标志,则会抛出TypeError
。 g
标志用于全局搜索,这意味着该标志指示我们在字符串的所有匹配项上测试正则表达式。
matchAll() 返回值
- 返回一个包含匹配项(包括捕获组)的迭代器。
注意:返回的迭代器的每个项目将具有以下附加属性:
- groups - 一个命名捕获组的对象,其键为名称,值为捕获的匹配项。
- index - 找到结果的搜索索引。
- input - 搜索字符串的副本。
示例 1:使用 matchAll() 方法
// string definition
const sentence= "I am learning JavaScript not Java.";
// pattern having 'Java' with any number of characters from a to z
const regex = /Java[a-z]*/gi;
// finding matches in the string for the given regular expression
let result = sentence.matchAll(regex);
// converting result into an array
console.log(Array.from(result));
输出
[ 'JavaScript', index: 14, input: 'I am learning JavaScript not Java.', groups: undefined ] [ 'Java', index: 29, input: 'I am learning JavaScript not Java.', groups: undefined ]
在上面的示例中,我们定义了一个带有/g
标志的正则表达式 regex。然后我们调用了 sentence 中的 matchAll()
方法。
sentence.matchAll(regex)
将 sentence 字符串与包含“Java
”后跟任意数量的“a 到 z”字符的模式进行匹配。
对于给定的 regex,该方法找到了两个匹配项:“JavaScript
”和“Java
”。
注意:matchAll()
方法的输出结果是对象,因此我们使用 Array.from(result)
将其转换为数组。
示例 2:matchAll() 中的区分大小写的 regex
正则表达式(regex)是区分大小写的。我们可以在 matchAll()
方法中使用 i
标志使其不区分大小写。例如:
// string definition
const bio = "His name is Albert and albert likes to code.";
// pattern having 'albert' or 'Albert'
const regex = /albert/gi;
// finding 'albert' or 'Albert' in the string
const result = bio.matchAll(regex);
console.log(Array.from(result));
输出
[ [ 'Albert', index: 13, input: 'His name is Albert and albert likes to code.', groups: undefined ], [ 'albert', index: 24, input: 'His name is Albert and albert likes to code.', groups: undefined ] ]
在这里,我们在 regex 中使用了 i
标志和 g
标志(/albert/g
),这使其不区分大小写。因此,该方法返回一个包含两个迭代器的数组,其中包含找到的匹配项:“Albert
”和“albert
”。
另请阅读