I'd assume that the contract of s.indexOf(b) is to return the smallest integer r such that s.substring(r, r + b.length) == b.
When b is "", that result is 0.
In my opinion, most string functions like this shouldn't allow "" as an argument, because they are at least somewhat ambiguous. However, the unformity of allowing any string as the needle to search for is also nice, and in this particular case returning 0 is not so strange. I have more distaste for .replace("", "x") and .split("") which have truly ambiguous meanings.
You're right, .replace("", "x") and .split("") definitely have ambiguous meanings.
One thought I just had now though is thinking what if replace was using indexOf internally. Without a special case for an empty string, it could easily get stuck replacing the character at index 0 because indexOf said it found it there.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I'd assume that the contract of
s.indexOf(b)is to return the smallest integerrsuch thats.substring(r, r + b.length) == b.When
bis"", that result is0.In my opinion, most string functions like this shouldn't allow
""as an argument, because they are at least somewhat ambiguous. However, the unformity of allowing any string as the needle to search for is also nice, and in this particular case returning0is not so strange. I have more distaste for.replace("", "x")and.split("")which have truly ambiguous meanings.You're right,
.replace("", "x")and.split("")definitely have ambiguous meanings.One thought I just had now though is thinking what if
replacewas usingindexOfinternally. Without a special case for an empty string, it could easily get stuck replacing the character at index0becauseindexOfsaid it found it there.