To make sure it is not just me, let's look at a sample in C# and Python.
C#
Assert.AreEqual(7, "baa bb aa".LastIndexOf("aa")); // <= 7 Assert.AreEqual(1, "baa bb aa".LastIndexOf("aa", 5)); // Start search from position 5 <= 1 // Not found Assert.AreEqual(-1, "baa bb aa".LastIndexOf("aa", 1)); // Start search from position 1 <= -1
Python
"baa bb aa".rfind("aa") # <= 7 "baa bb aa".rfind("aa", 0, 5) # <= 1 # Not found "baa bb aa".rfind("aa", 0, 1) # <= -1
So far, so good.
JavaScript
"baa bb aa".lastIndexOf("aa") // <= 7 "baa bb aa".lastIndexOf("aa", 5) // <= 1 // Found, What ? "baa bb aa".lastIndexOf("aa", 1) // <= 1
You can read the spec at 15.5.4.8 String.prototype.lastIndexOf (searchString, position)
Here is the summary:
If searchString appears as a substring of the result of converting this object to a String at one or more positions that are smaller than or equal to position, then the index of the greatest such position is returned; otherwise, ‑1 is returned.
Let's simplify the definition, to avoid the part of conversion, which is not my point in this blog.
If searchString appears as a substring IN THE STRING at one or more positions that are smaller than or equal to THE position PARAMETER, then the index of the greatest such position is returned; otherwise, ‑1 is returned.
Once you read the definition about 5 times and try to apply to my example, yes
"baa bb aa".lastIndexOf("aa", 1) // <= 1
The question is why? What is so special about the ECMAScript 5 comity that they came up with such an idea?
The MOZILLA definition has a different summary String.prototype.lastIndexOf(), which is more confusing.
Syntax
str.lastIndexOf(searchValue[, fromIndex])Parameters
searchValue - A string representing the value to search for.fromIndex - The location within the calling string to start the search at, indexed from left to right. It can be any integer between 0 and the length of the string. The default value is the length of the string.
This definition could also be right, because of the part: indexed from left to right, I think, I guess, I hope, who really knows.
And to finish w3schools does not mention any special about the behavior.
No comments:
Post a Comment