My word finder not working: do-while Loop problem

Viewed 31

Im trying to make a word finder but it shows error in the do while loop. Maybe there's a problem with the exec() function. here's my JavaScript:

const words = [/lorem/gi, /ipsum/gi];

const body = document.body;

let log = [];

for (const w of words) {
  let yes = true;

  let theWord = w.exec(String(body.innerHTML));
  loo: do {
    console.log(theWord == null);
    if (theWord == null) {
      yes = false;
      console.log(yes);
      break loo;
    } else {
      log.push(theWord);
    }
  } while (yes == true);
}

console.log(log);

i'll do the styling on the page later using index and span; but for now, please help me with this

html:

<body>

    <h1>Ipsum Lorem</h1>
    <h1>lorem Ipsum</h1>
    <h1>Lorem ipsum</h1>
    <h1>lorem ipsum</h1>
    <h1>LoRem iPsUm lOrEm Lorem</h1>

    <span style="display: block;">lorem ipsum</span>

    <br>

    <b style="display: block;">LoReM iPsUm</b>

    <br>

    <i style="display: block;">lOrEm IpSuM</i>

    <br>

    <a href="#">ipSUM LORem</a>

    <br>
    <br>

    lorem IPSUM

    <br>
    <br>

        <div>
            LOREM ipsum
        </div>

<style>
    body {
        background-color: #444;
        color: #fff;
    }
</style>

</body>

I edited the question as one asked to show the html.

1 Answers

The problem is that you never change theWord inside the loop. So if theWord is not null in the first iteration, it also will not be in the second or any other iteration of the loop: so the loop will hang.

You need to assign to theWord the result of exec inside the loop.

Just by moving that line into the loop, the code works:

const words = [/lorem/gi, /ipsum/gi];

const body = document.body;

let log = [];

for (const w of words) {
  let yes = true;
  loo: do {
    let theWord = w.exec(String(body.innerHTML));
    console.log(theWord == null);
    if (theWord == null) {
      yes = false;
      console.log(yes);
      break loo;
    } else {
      log.push(theWord);
    }
  } while (yes == true);
}

console.log(log);

There is much to comment on this code, such as:

  • Don't do yes == true when yes is a boolean. Just test the boolean
  • Don't introduce another variable like yes, when the loop condition is simply theWord being not null.
  • When the while condition is evaluated, it will always be true, since otherwise the break had been executed. So this could be just do ... while(true).
  • To collect all matches it is not needed to use .exec. There is the string .match method (which takes a regex as argument), that does this collecting for you out of the box.
Related