'Develop a JavaScript to Find the position of 3rd occurrence of the given string “efg” I/P:abcefgacefgabcceftyefghjklop O/p:20

I developed a logic for the above problem but i couldnt get the desired result.

    function thirdOccurence(string){
    var count = 0;
    var i=0;
    var result = 0;
    while(i<string.length){
    if(string[i]=='e' && string[i+1]=='f' && string[i+2]=='g')
    {
        count = count+1;
        i+3;
        if(count==3)
        {
                result = i+1;
                break;
        }
    }
    else
        i++;
    }     
    }*

here the string is the input - abcefgacefgabcceftyefghjklop -output should be 20 since we need to find position. I have a working code but with a different logic. But i need to know why this is not working.



Solution 1:[1]

The problem was with the line where you increment the i variable by 3: i += 3. This meant you jumped 3 indexes forward, before the final condition if(count==3). But if you increment i by 3 after this final condition - everything works as expected :)

function thirdOccurence(string) {
  var count = 0;
  var i = 0;
  var result = 0;
  while (i < string.length) {
    if (string[i] === "e" && string[i + 1] === "f" && string[i + 2] === "g") {
      count += 1;
      if (count === 3) {
        result = i + 1;
        break;
      }
      i += 3;
    } else {
      i++;
    }
  }
  return result
}

console.log('result should be 20:', thirdOccurence('abcefgacefgabcceftyefghjklop'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Max