user3528358
user3528358

Reputation: 1

is this a javascript issue on lastIndexOf?

The W3C write

string.lastIndexOf(searchvalue,start)

The string is searched from the end to the beginning, but returns the index starting at the beginning, at postion 0. This method returns -1 if the value to search for never occurs.

start is Optional. The position where to start the search (searching backwards). If omitted, the default value is the length of the string

Demo:

var str = Larry Ullman;
str.lastIndexOf('a', 5);

return => 1

it look like true but..

var str = "abcdbef";
str.lastIndexOf('d',1); //=> -1
str.lastIndexOf('d',2); //=> -1

Why it return -1 not 3 ??

Upvotes: 0

Views: 64

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

Because it is searching backwards from 1 and 2 index. And there is no d before abc of the str

The second parameter says to search backward from the given index.

var str = "abcdbef";
str.lastIndexOf('d',1); // it is searching backwards for d from first b and there is no d so -1

Upvotes: 1

Related Questions