Skip to content
Advertisement

RegExp.prototype.exec() can loop forever

Steps to reproduce:

This will result in an infinite loop. How do I prevent this from happening? In my Node application, the user can specify .* as the pattern and it hangs. I do not think doing a string-match and preventing this specific regex pattern would help as there might be many other patterns that will result in an infinite loop.

Source code (in case the content of the MDN page changes):

const regex1 = RegExp('.*', 'g');
const str1 = 'text';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(array1.index);
}

Advertisement

Answer

All patterns that can match an empty string exhibit this behaviour – see Regex that can match empty string is breaking the javascript regex engine or Zero-Length regexes and infinite matches?.

The simple solution would be to just use matchAll instead testing for some complicated loop condition yourself:

const regex = /.*/g;
const str = 'text';
for (const match of str.matchAll(regex)) {
  console.log(match.index, match[0]);
}

Alternatively, using str.match(regex) instead of regex.exec(str) would also help.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement