DEV Community

Discussion on: What happens when you IndexOf an empty string?

Collapse
 
curtisfenner profile image
Curtis Fenner

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.

Collapse
 
turnerj profile image
James Turner

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.