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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...