DEV Community

Cover image for String.indexOf() and .lastIndexOf() | Javascript
tran0460
tran0460

Posted on

String.indexOf() and .lastIndexOf() | Javascript

String.indexOf()

The String.indexOf() method returns the index inside the object String of the value you pass inside the parentheses (). The value can either be a string or a number, as long as they exist inside the String object.

Example:

let myString = "December 11th"

console.log(myString.indexOf("c"))
console.log(myString.indexOf(1))

//output:
2
9  
Enter fullscreen mode Exit fullscreen mode

If you pass in multiple letters or numbers, the index of the first letter/number is returned

let myString = "Friday April 4th 2044"

console.log(myString.indexOf("r"))
console.log(myString.indexOf("April"))
console.log(myString.indexOf(4))
console.log(myString.indexOf(2044))

//output:
1
7
13
17
Enter fullscreen mode Exit fullscreen mode

String.lastIndexOf()

The String.lastIndexOf() method basically does the same thing, but here's how they differ from each other :

String.indexOf() returns the index of the first appearance of the value. In other words, it starts looking from the beginning to the end of the string.

String.lastIndexOf() returns the index of the last appearance of the value. Simply put, it starts looking from the end to the beginning of the string.

Note: The index will always be counted from the beginning

Example:

let myString = "Friday April 4th 2044"

console.log(myString.lastIndexOf(4))
console.log(myString.lastIndexOf("r"))

//output:
20
9
Enter fullscreen mode Exit fullscreen mode

Notice how the index of 4 and r is now different from the previous example, it is because .lastIndexof() starts looking from the end.

The rule also applies if you pass in multiple letters/numbers

let myString = "EMMA'S DILEMMA"

console.log(myString.indexOf("EMMA"))
console.log(myString.lastIndexOf("EMMA"))

//output:
0
10
Enter fullscreen mode Exit fullscreen mode

So what if you pass in a value that doesn't exist inside the string?

let myString = "December 11th"

console.log(myString.indexOf("X"))
console.log(myString.lastIndexOf("october"))

//output:
-1
-1
Enter fullscreen mode Exit fullscreen mode

If the value doesn't exist, -1 is returned

Reference Material

If you still have any questions about .indexOf() and lastIndexOf(), I recommend checking out this awesome video:

Top comments (0)