JavaScript indexOf and lastIndexOf methods and how to use them.

JavaScript indexOf and lastIndexOf methods and how to use them.

indexOf() and lastIndexOf() are string methods in JavaScript that are used to search for a substring within a given string. The indexOf() method returns the index of the first occurrence of the specified substring, while the lastIndexOf() method returns the index of the last occurrence of the specified substring.

Here's an example of using the indexOf() method:

In the example above, the indexOf() method is used to search for the index of the first occurrence of the letter "o" in the string "Hello World". The method returns the index value 4, which is the index of the first occurrence of the letter "o" in the string.

Here's an example of using the lastIndexOf() method:

In the example above, the lastIndexOf() method is used to search for the index of the last occurrence of the letter "o" in the string "Hello World". The method returns the index value 7, which is the index of the last occurrence of the letter "o" in the string.

Both methods return -1 if the specified substring is not found in the string. It's important to note that both methods are case sensitive.

Thanks for reading and learning ❤️

#LetsCodeIt