-3

For some reason, my indexOf 2nd arg (where to start the search) is not working. It just always returns 4 or -1. Where string test = "Bob jr" and I am using built-in JavaScript console on about:blank:

> var test = "Bob jr";
> test.indexOf('j', 0);
< 4 = $3
> test.indexOf('j', 1);
< 4 = $3
> test.indexOf('j', 12);
< -1 = $2

Why is this not working and how can I get it working?

1
  • 4
    as the j doesn't move, it would be in the same place every time - in other words, the returned value isn't relative to the start position of the search Commented Feb 21, 2016 at 11:42

3 Answers 3

6

Whether you start looking at 0 or index 1, the j is still at index 4.

Your final example proves the argument does work, because you said to start after the j (beyond the end of the string entirely), and sure enough, it didn't find it.

Let's see indexOf's second argument in action:

var str = "j and j and j x";
console.log("Search string: '" + str + "'");
for (var n = 0; n < str.length; ++n) {
    test(str, n);
}
function test(s, start) {
    var index = s.indexOf("j", start);
    console.log("Starting at " + start + ": " + index);
}

If you want to find out how far after the index you've given it is to the j, you can do that in two ways:

  1. Subtract your index from the result you get:

     console.log("Distance: " + (test.indexOf('j', 1) - 1));
    
  2. Search a substring:

     console.log("Distance: " + test.substring(1).indexOf('j');
    
0

Check the documentation of indexOf here

str.indexOf(searchValue[, fromIndex])

There is no j after position 12 and that is why you are getting -1 in the last case.

0

indexOf always return the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. The reason your return value isn't changing is because "j" is still the 5th character in your string, regardless of whether you begin your search a few characters into the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.