Javascript Regex matchAll函数不起作用

问题描述

每当我运行下面的代码时,都会出现错误TypeError: responseData.matchAll is not a function

    var responseData = response.data.toString(); 
    var regex = new RegExp('(<dbname>)(.*?)(?=<\/dbname>)','g'); 

    var matches = responseData.matchAll(regex);
    

当我将matchAll替换为exec时,它起作用了!但是,我需要使用matchAll。这真让我抓狂。谢谢

解决方法

如果您需要matchAll,请在支持的情况下使用它:

var responseData = "<dbname>hhh</dbname>hhh<dbname>hhh3</dbname>"; 
var regex = new RegExp('<dbname>(.*?)(?=</dbname>)','g'); 
console.log(Array.from(responseData.matchAll(regex),x=>x[1]));
// => ["hhh","hhh3"]
   

您也可以使用exec

var responseData = "<dbname>hhh</dbname>hhh<dbname>hhh3</dbname>"; 
var regex = new RegExp('<dbname>(.*?)(?=</dbname>)','g'); 
while(match=regex.exec(responseData)){
  console.log(match[1]);
}

,

matchAll很新,仅在某些浏览器中有效。它可以在Chrome,FX,Edge和Safari中运行,但是较旧的移动浏览器可能需要填充程序/填充。

以下是使用垫片将功能添加到旧版浏览器的好答案:https://stackoverflow.com/a/58003501/905