Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over RegExp.exec(...)

Tags:

javascript

From the RegExp.exec page on MDN, it gives the following example of iterating through a match with the g flag set:

const regex1 = RegExp('foo*', 'g');
const str1 = 'table football, foosball';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // expected output: "Found foo. Next starts at 9."
  // expected output: "Found foo. Next starts at 19."
}

I have two questions about this code. The first one is why the !=== null is used here, why wouldn't the while loop be properly coded as:

while (array1 = regex1.exec(str1)) { // implicitly casts to boolean?
  console.log(`...`);

}

The above seems much more readable to me, but was wondering why the MDN docs used the first approach? Second, is it possible to declare and define the variable directly in the while loop? Something like:

while (let array1 = regex1.exec(str1)) { // don't need the `let array1` above?
  console.log(`...`);

}

Or is that not supported in the JS language?

like image 645
samuelbrody1249 Avatar asked Oct 24 '25 16:10

samuelbrody1249


1 Answers

Why the !== null is used here...?

True, in this case it is not needed. .exec() returns either an array or null, and since arrays are always truthy there is no need to explicitly compare with null.

Is it possible to declare and define the variable directly in the while loop?

No. If you want that, then turn to the for loop, which does support this:

for (let array1; array1 = regex1.exec(str1); null) {
  console.log(`...`);
}

This does indeed have the advantage that array1 has a more restricted scope. NB: I provided null to stress that the third part of the for header is intentionally unused.

like image 83
trincot Avatar answered Oct 26 '25 06:10

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!