Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between string.indexOf() and string.lastIndexOf()? [closed]

Tags:

javascript

What's the difference between string.indexOf() and string.lastIndexOf() in JavaScript?

var temp = state.indexOf("tmp");    
var temp = state.lastIndexOf("tmp");
like image 621
Asieh hojatoleslami Avatar asked Aug 18 '14 05:08

Asieh hojatoleslami


4 Answers

From MDN :

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value

So the indexOf will return first occurrence of the value and the lastIndexOf will return the last occurence of the value.

Example (copied from MDN):

var anyString = "Brave new world";
var a = anyString.indexOf("w")); // result = 8
var b = anyString.lastIndexOf("w")); // result 10

Both of the method return -1 if the value is not found

More :

  • indexOf
  • lastIndexOf
like image 57
Iswanto San Avatar answered Sep 24 '22 19:09

Iswanto San


string.indexOf() method returns the position of the first occurrence of a specified value in a string.

string.lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

like image 27
Manu Benjamin Avatar answered Sep 23 '22 19:09

Manu Benjamin


indexOf() function is match first occurance, LastindexOf() function is match last occurance

Both function are using for finding index in String or Array;

sample code with String operation

var state = "abcdtmpefgtmp";
var temp =state.indexOf("tmp"); //match first occurance
console.log(temp);
//>4

var temp =state.lastIndexOf("tmp"); //match last occurance
console.log(temp);
//>10

sample code with Array operation

var state = ["abc", "tmp", "efg", "tmp"];
var temp =state.indexOf("tmp");
console.log(temp);
//>1
var temp = state.lastIndexOf("tmp");
console.log(temp);
//>3
like image 38
Girish Avatar answered Sep 25 '22 19:09

Girish


The lastIndexOf() method returns the position of the last occurrence of a specified value in a string, where as indexOf() returns the position of the first occurrence of a specified value in a string.

In the following example:

 function myFunction() {
     var str = "Hello planet earth, you are a great planet.";
     var n = str.lastIndexOf("planet");
     var n2 = str.indexOf("planet");

 }

n will return 36 and n2 will return 6

Please let me know if you have any questions!

like image 35
Devarsh Desai Avatar answered Sep 22 '22 19:09

Devarsh Desai