0

Let's say I have a string: var a = 'testString';

Then I got the index of t:

return a.indexOf('t');

That would give 0. Now I'm going to get the index of '':

return a.indexOf('');

That also gives 0, yet if I return a.charAt(0) it returns 't'. How is it possible for a.indexOf('') and a.indexOf('t') both be 0?

Cilan
  • 13,101
  • 3
  • 34
  • 51
  • 1
    what do you mean by index of `''` an empty string – Arun P Johny Dec 24 '13 at 01:07
  • 1
    @falinsky - JavaScript != Java. – nnnnnn Dec 24 '13 at 01:22
  • @nnnnnn Lol, it doesn't matter the language, an empty string is still an empty string... – Cilan Dec 24 '13 at 01:23
  • 1
    @ManofSnow - You can't assume all languages will behave the same way for `.indexOf()` or other string searching functions, so it's not really a true duplicate. Though for JS and Java I guess they do behave the same way, and I do like the [accepted answer](http://stackoverflow.com/a/2683509/615754) in that other question. – nnnnnn Dec 24 '13 at 01:24
  • @nnnnnn sure, you're right – falinsky Dec 24 '13 at 01:25
  • 2
    Note that in answer to "How can index be two things at once?", with your example string `a.indexOf('test')` returns the same index as `a.indexOf('testString')` and `a.indexOf('t')`... That is, `.indexOf()` is not doing the same thing as `.charAt()`. – nnnnnn Dec 24 '13 at 01:29

1 Answers1

4

Because the empty string is a substring of every string. indexOf is specified to return the smallest index which matches the substring, so the index returned for any string will always be 0.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83