The syntax of indexOf method is as below :
str.indexOf(subStr [, startIndex])
It takes two parameters, one is optional.
subStr : This is the sub string to find in the string str.
startIndex : This is an optional integer value to define the start index from where the search should begin. By default, it’s value is 0 i.e. the search starts from the first character of the string.
Let’s take a look at the example below :
let str = "The quick brown fox jumps over the lazy dog"; //1 console.log(str.indexOf("The")); //2 console.log(str.indexOf("the")); //3 console.log(str.indexOf("h")); //4 console.log(str.indexOf("h",5)); //5 console.log(str.indexOf("hello"));
0 31 1 32 -1
In this example :
- The first console.log statement prints 0 because the first occurrence of ‘The’ is at index 0 in the string.
- The second console.log statement prints 31 because the first occurrence of ‘the’ is at index 31 in the string.
- The first occurrence of ‘h’ is at index 1.
- The first occurrence of ‘h’ is at index 32 if the search starts at index 5 .
- The substring ‘hello’ is not available in the given string. So, it prints -1 .