Ben Gubler
Ben Gubler

Reputation: 1441

RegExp match with lastIndex results in infinite loop

The following code always results in an infinite loop, and I have no idea why.

var regex1 = /Hi([^]*?)Hi/g
var str = `
Hi my name is Hi
`;

function doStuff(str) {
  var lastMatchIndex = 0
    while ((m = regex1.exec(str)) !== null) {
        console.log("it's not null")
        //firstblock is the content between the 2 hi's
        var firstblock = m[1] || ""
        if (firstblock !== "") {
            console.log(doStuff(firstblock))
        }
    }
    return str
}
doStuff(str)

I would assume that the while loop would occur once, and firstblock would be equal to " my name is ". When I called console.log(doStuff(firstblock)) there would be no matches, so the while loop would not execute, and it would print " my name is " to the screen. What's going wrong?

I'll attach an example, BUT IT MAY CRASH YOUR BROWSER TAB. BE WARNED. :)

Upvotes: 1

Views: 49

Answers (1)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You are missing return; inside the if condition to prevent infinite loop from the outer recursion function. The console.log(doStuff(firstblock)) will call the doStuff function second time and then this second call will simply return str. The control is passed to the calling recursive function and now this function needs to return the control to doStuff(str) otherwise the while loop will execute infinitely.

var regex1 = /Hi([^]*?)Hi/g
var str = `Hi my name is Hi`;

function doStuff(str) {
  var lastMatchIndex = 0
  while ((m = regex1.exec(str)) !== null) {
    console.log("it's not null")
    //firstblock is the content between the 2 hi's
    var firstblock = m[1] || ""
    if (firstblock !== "") {
        console.log(doStuff(firstblock));
        return;
    }
  }
  return str
}
doStuff(str)

Upvotes: 1

Related Questions