Question

string.lastIndexOf(searchValue[, fromIndex])

MDN says that fromIndex default value is equal to the string.length, however, I really think it is string.length-1

But it doesn't matter what I think... I need someone to confirm what is the default value of fromIndex

Here is what they say:

"It can be any integer between 0 and the length of the string. The default value is the length of the string."

Was it helpful?

Solution

According to ECMAScript 5, it will be the length of the String.

15.5.4.8 String.prototype.lastIndexOf (searchString, position)

If position is undefined, the length of the String value is assumed, so as to search all of the String.

...

  1. Call CheckObjectCoercible passing the this value as its argument.
  2. Let S be the result of calling ToString, giving it the this value as its argument.
  3. Let searchStr be ToString(searchString).
  4. Let numPos be ToNumber(position). (If position is undefined, this step produces the value NaN).
  5. If numPos is NaN, let pos be +∞; otherwise, let pos be ToInteger(numPos).
  6. Let len be the number of characters in S.
  7. Let start min(max(pos, 0), len).
  8. Let searchLen be the number of characters in searchStr.
  9. Return the largest possible nonnegative integer k not larger than start such that k+ searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the character at position k+j of S is the same as the character at position j of searchStr; but if there is no such integer k, then return the value -1.

OTHER TIPS

It doesn't matter, at all. Since the index is zero-based, both string.length and string.length-1 will include the entire string.

EDIT

You can test for differences in the result pretty simply:

var s = '01923456789abcdef';
alert(s.lastIndexOf('f',s.length+1));
alert(s.lastIndexOf('f',s.length));
alert(s.lastIndexOf('f',s.length-1));
alert(s.lastIndexOf('f',s.length-2));

That alerts 16, 16, 16, -1. Thus, if you are very concerned with an extra few cycles being used when a useragent runs .lastIndexOf(), you can pass .length-1 and have it spend a few extra cycles parsing the extra parameter.

If fromIndex is as large or larger than the string length, the function returns -1.

If not, the string.substring(fromIndex) searches from the end of the substring.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top