Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matchAll Throws error when g flag is missing now?

From the MDN docs it states

matchAll only returns the first match if the g flag is missing.

But if you run this code:

const regexp = RegExp('[a-c]', '');
const str = 'abc';
console.log(Array.from(str.matchAll(regexp), m => m[0]));
// Array [ "a" ]

in a recent version of chrome you get the following error:

Error: undefineds called with a non-global RegExp argument

I'm on chrome version 80.0.3987.116

I'm not sure if this is a chrome issue or the MDN documentation needs to be updated.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll

like image 682
David Fann Avatar asked Feb 18 '20 21:02

David Fann


People also ask

What is the G in regex?

The g flag indicates that the regular expression should be tested against all possible matches in a string.

What is matchAll in JavaScript?

matchAll() The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups.

How do I find all matches in regex?

To find find all the matches of a regular expression in this string in JavaScript, call match() method on this string, and pass the regular expression as argument. match() method returns an array of strings containing all the matches found for the given regular expression, in this string.

Which of the following regexp methods will return a true if a pattern match is present in a string?

exec(str) The regexp. exec(str) method returns a match for regexp in the string str .


Video Answer


1 Answers

The information presented to you on MDN, in this instance, is wrong.

The Official ECMA Specification, ECMA-262 as of February 15, 2020( See here ), states that if there is no g flag present, that matchAll should throw a TypeError.

See specifically 2.b.iii below.


matchAll MDN


The error message is obviously fairly confusing with its phrasing, but still correct.

like image 109
zfrisch Avatar answered Oct 08 '22 22:10

zfrisch