Open In App

JavaScript String indexOf() Method

The JavaScript String indexOf() method finds the index of the first occurrence of the argument string in the given string. The value returned is 0-based.

The indexOf() method is case sensitive.



Syntax:

str.indexOf(searchValue , index);

Parameters: 

Return value: 

The first position is where the search value occurs. -1 if it never occurs.

Example 1: Below is an example of the String indexOf() Method. 






function func() {
 
    // Original string
    let str = 'Departed Train';
 
    // Finding index of occurrence of 'Train'
    let index = str.indexOf('Train');
    console.log(index);
}
func();

Output
9

Example 2: In this example, the indexOf() method finds the index of the string ed Tr. Since the first and only index where this string is present is 6, therefore this function returns 6 as the answer.




// JavaScript to illustrate indexOf() method
function func() {
 
    // Original string
    let str = 'Departed Train';
 
    // Finding index of occurrence of 'Train'
    let index = str.indexOf('ed Tr');
    console.log(index);
}
func();

Output
6

Example 3: In this example, the indexOf() method finds the index of the string Train. Since the searchValue is not present in the string, therefore this function returns -1 as the answer.




function func() {
 
    // Original string
    let str = 'Departed Train';
 
    // Finding index of occurrence of 'Train'
    let index = str.indexOf('train');
    console.log(index);
}
func();

Output
-1

Example 4: In this example, the indexOf() method finds the index of the string Train. Since the first index of the searchValue is 9, therefore this function returns 9 as the answer.




function func() {
 
    // Original string
    let str = 'Departed Train before another Train';
 
    // Finding index of occurrence of 'Train'
    let index = str.indexOf('Train');
    console.log(index);
}
func();

Output
9

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported browser:


Article Tags :