What is the default value of lastIndexOf?
-
27-10-2019 - |
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."
Solution
According to ECMAScript 5, it will be the length
of the String.
15.5.4.8 String.prototype.lastIndexOf (searchString, position)
If
position
isundefined
, thelength
of the String value is assumed, so as to search all of the String....
- Call
CheckObjectCoercible
passing the this value as its argument.- Let
S
be the result of callingToString
, giving it the this value as its argument.- Let
searchStr
beToString(searchString)
.- Let
numPos
beToNumber(position)
. (If position is undefined, this step produces the valueNaN
).- If
numPos
isNaN
, let pos be+∞;
otherwise, letpos
beToInteger(numPos)
.- Let
len
be the number of characters inS
.- Let
start
min(max(pos, 0), len)
.- Let
searchLen
be the number of characters insearchStr
.- 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.