JavaScript(JS) string method - indexof

https‮.www//:‬theitroad.com

The indexOf() method is a string method in JavaScript that is used to find the first occurrence of a specified substring in a given string. It returns the index of the first occurrence of the specified substring, or -1 if the substring is not found.

Here is the syntax for the indexOf() method:

str.indexOf(searchValue[, fromIndex])

Here, str is the original string you want to search in, and searchValue is the substring you want to search for. The optional fromIndex parameter specifies the position within the str to start the search from, and if not specified, it starts from the beginning of the string.

The indexOf() method returns the index of the first occurrence of the specified substring within the string. If the substring is not found, it returns -1.

Here is an example of using the indexOf() method:

let str = "Hello World";
console.log(str.indexOf("o")); // 4
console.log(str.indexOf("x")); // -1
console.log(str.indexOf("o", 5)); // 7

In the first console.log(), the indexOf() method returns 4 because the first occurrence of the substring "o" in the str is at the 4th index. In the second console.log(), it returns -1 because the substring "x" is not found in the str. In the third console.log(), it returns 7 because the first occurrence of the substring "o" in the str after the 5th index is at the 7th index.