4

I really dont understand how lastIndexOf works. I could not get the usage of second optional parameter.

string.lastIndexOf(searchvalue,start)

searchvalue -> Required. The string to search for

start -> Optional. The position where to start the search. If omitted, the default value is the length of the string

var test = "mississippi";

test.lastIndexOf("ss",1) // return -1
test.lastIndexOf("ss",2) // returns 2
test.lastIndexOf("ss",5) // returns 5

Could anyone tell me the idea step by step ? Why first one returns -1 and second one returns 2 for example ?

TIA

Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105

2 Answers2

5

Its because thats the starting index. -1 means not found.

m 0
i 1
s 2
s 3
i 4
s 5
s 6
i 7
p 8
p 9
i 10

So starting at 1 and I dont see a match. But with 2, I see s then s at 3.

MDN explains it well.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 1
    To elaborate, it's the starting point of the search, and the search is performed backwards. If the argument is `1`, only the first two characters of the string are searched. If it is `5`, all characters up to the sixth (inclusive and counting from 1) are searched. – Frédéric Hamidi Sep 14 '12 at 18:58
  • ok. Then I am looking for 'ss' and I give it 5 as a second parameter. Why it gives me 5 as a result. Because the second 's' is the sixth character. Shouldnt it look for up to 5 – Barış Velioğlu Sep 14 '12 at 19:05
  • @Ryu, nope, the second `s` has *index* 6. It's the seventh character in the string, assuming you're counting from 1. The function returns `5` because it starts searching at index `5` (the first `s`) and sees `ss` from this position (the rest of the string stills counts). – Frédéric Hamidi Sep 14 '12 at 19:06
  • @FrédéricHamidi you're saying that "If the argument is 1, only the first two characters of the string are searched" then if the argument is 2, shouldn't it be only the first three characters are searched? which in this case would be "mis" and should have returned -1? – Hazem Salama Sep 14 '12 at 19:31
  • @hsalama, that's tricky indeed, that's why I said `the rest of the string stills counts` in my previous comment. The search is performed backward from the start index, but the whole string is still considered. Passing `1` searches for `ss` at the *start* of `ississipi`, then `mississippi` (none match). Passing `2` searches for `ss` at the start of `ssissippi`, which matches. Passing `5` searches for `ss` at the start of `ssippi`, which also matches. *(I don't think I can explain it better in comments, but I can edit Daniel's answer with ugly ASCII art if I have to :)* – Frédéric Hamidi Sep 14 '12 at 19:41
-1

The lastIndexOf() method gets the last index of a search string in the main string. It takes one parameters as input a search string.

It returns the the last position (index) of the search string. If the search string can not be found it will return "-1". Visit http://skillcram.com/JS.htm for example

Apte Lowel
  • 11
  • 1