What's the difference between string.indexOf()
and string.lastIndexOf()
in JavaScript?
var temp = state.indexOf("tmp");
var temp = state.lastIndexOf("tmp");
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 :
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.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With