lastIndexOf reports 0 when the char is also at pos 0.




9 years ago
9 years ago


(Reporter: danswer, Unassigned)


Firefox Tracking Flags

(Not tracked)




9 years ago
User-Agent:       Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20070508 Firefox/
Build Identifier: FF 1.5-3.5

alert ("abcdabcdabcd".lastIndexOf("a", -1))
alert ("abcdabcdabcd".lastIndexOf("b", -1))

Reproducible: Always

Actual Results:  
0 is returned in the first case, which seems incorrect.

Expected Results:  
I would expect either a -1 or 8 depending on how a negative number in the 2nd argument is treated (ie. negative argument always means not found => -1; or negative argument => string.length - arg2), but in no case a 0.

This stretches back to at least FF 1.5
But what really makes me scratch my head is that it happens from IE 6 - IE 8, so I have to wonder if I'm missing something...

Comment 1

9 years ago
(In reply to comment #0)
> But what really makes me scratch my head is that it happens from IE 6 - IE 8,
> so I have to wonder if I'm missing something...

It seems that what you are missing is the spec. In section start is adjusted to be in the range 0..length of string [taking the readable version:
Let start min(max(pos, 0), len) ]
Last Resolved: 9 years ago
Resolution: --- → INVALID
The Pythonic "-1 means last index in sequence" treatment of negative indexes applies only to slice and substr, alas. I should say "Perlish" for the latter. The rest suffer from Java's less useful influence.


Comment 3

9 years ago
John, thanks for pointing that out.  It is indeed well embedded in the spec and not an FF issue.

Brendan, my issue wasn't with the fact that
str.split('').lastIndexOf(chr, index) != str.lastIndexOf(chr, index)
for certain negative indeces.

Rather, that it strikes me that - step 7 at is inconsistent.  It seems to me that in overeagerness to accomodate the search string being empty, the
possibility that the search string being at the start
of the string was not well accounted for, or at least
I certainly don't see the driving rationale.

I would have rewritten step 7 and 9 to be something like:
Step 7: Let start min(pos, len)
Step 9: ... ; but if there is no such integer k,
        then return the value -min(1,searchLen)

The only difference between and the above is that if pos is negative and searchStr is a prefix of S, the above produces a -1 instead of a 0.  All that is water under the bridge at this point; I'm just sorry I wasn't aware of it much earlier to have chimed in.

Csaba Gabor from Vienna

Comment 4

9 years ago
Expecting a driving rationale from all parts of a bit of a reach.  ;-)  Sorry, that's just how it happened, and it's water under the bridge at this point that JavaScript has internal inconsistencies.  We live with them, maybe fix some in ES5's strict mode in some cases, and move with what we have.
You need to log in before you can comment on or make changes to this bug.