Paul Trimor
Paul Trimor

Reputation: 340

Javascript Regex matchAll function not working

whenever I run the code below I get en error TypeError: responseData.matchAll is not a function

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

    var matches = responseData.matchAll(regex);
    

When I replace matchAll with exec it works! However, I need to use matchAll. This is driving me crazy. Thanks

Upvotes: 2

Views: 7486

Answers (2)

Keith
Keith

Reputation: 155802

matchAll is pretty new, it only works in some browsers. It works in Chrome, FX, Edge and Safari, but older and mobile browsers may require a shim/polyfill.

Here is a good answer on using a shim to add the functionality to older browsers: https://stackoverflow.com/a/58003501/905

Upvotes: 1

Ryszard Czech
Ryszard Czech

Reputation: 18631

If you need matchAll, use it if supported:

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"]
   

You can also use 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]);
}

Upvotes: 7

Related Questions