-1
    let str = "Hello world";
    let target = "o";
    let pos = -1;
    while ((pos = str.indexOf(target, pos + 1)) != -1) {
      console.log( pos );
    }

When pos is - 1 it works fine, but when I set 0 and remove + 1 it returns endless 4. Why does it happen?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Alexander
  • 9
  • 1
  • 4
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Nov 30 '22 at 14:56
  • `pos + 1`; what happens here if you use 0 vs -1? – mykaf Nov 30 '22 at 15:01
  • string.indexOf(searchvalue, start), https://www.w3schools.com/jsref/jsref_indexof.asp . Will work depending on the size of target and the start parameter. – MZM Nov 30 '22 at 15:01
  • @mykaf basically it'll stop working if target is H... – Salketer Nov 30 '22 at 15:02

1 Answers1

2

If you do not increase the position, it repeats 4 indefinitely because you are always doing the exact same check. Removing variables and using just this part:

pos = str.indexOf(target, pos)

This would mean:

str.indexOf(target, 0) // Returns 4
str.indexOf(target, 4) // Returns 4
str.indexOf(target, 4) // etc

That's because indexOf will start looking at the exact index that it just found so it will find the o again. Adding +1 makes sure that it continues looking PAST last occurence found.

Salketer
  • 14,263
  • 2
  • 30
  • 58