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:
Subtract your index from the result you get:
console.log("Distance: " + (test.indexOf('j', 1) - 1));
Search a substring:
console.log("Distance: " + test.substring(1).indexOf('j');
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