Skip to content

String.matchAll(新的API)

获取正则表达式匹配的结果组的迭代器对象

主要区别于String.prototype.match()

String.prototype.match()

  • 只要有一个reject那么就立即结束

String.prototype.matchAll()

  • 只能作用域 //g
  • 返回的是一个Iterator迭代器
  • 返回的结果永远是一个 结果组

语法

js
str.matchAll(regexp)

参数

  1. regexp

正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。

RegExp必须是设置了全局模式g的形式,否则会抛出异常TypeError。

返回值

一个迭代器(不可重用,结果耗尽需要再次调用方法,获取一个新的迭代器)。

栗子

js
const str = "this is a str"

const ireg = /i/
const greg = /i/g

// 一个伪数组 { 
//   0: "i"
//   groups: undefined
//   index: 2
//   input: "this is a str"
//   length: 1
// }
console.log(str.match(ireg))   // [ "i" ]  

// 不是一组包含附加特性的结果数组,而是简简单单的数组
console.log(str.match(greg))  // [ "i" , "i" ]

// RegExp String Iterator {} 迭代器
console.log(str.matchAll(greg))

//  [[ "i" ] ,[ "i" ] ] ,详情见下图
console.log([...str.matchAll(greg)])

// 报错 Uncaught TypeError: matchAll must be called with a global RegExp
console.log([...str.matchAll(ireg)])

image-20210721160643287

结果:

可见String.prototype.matchAll()的主要作用是解决String.prototype.match()在匹配全局属性的时候,对于多个值的结果只返回匹配的内容,而没有匹配值的附加特性的问题。