JavaScript String indexOf() Method

Last Updated : 16 Jan, 2026

The indexOf() method is used to find the position of a value inside a string. It returns the index where the value first appears.

  • Returns the 0-based index of the first occurrence.
  • Used to locate a substring inside a string.
  • It is case-sensitive, so different letter cases are treated differently.
JavaScript
let text = "Hello World";

let position = text.indexOf("World");

console.log(position);

Syntax

str.indexOf(searchValue , index);

Parameters

  • searchValue: The searchValue is the string to be searched in the base string. 
  • index: The index defines the starting index from where the search value will be searched in the base string.

Return value

  • If the searchValue is found, the method returns the index of its first occurrence.
  • If the searchValue is not found, the method returns -1.

[Example 1] : Finding the First Occurrence of a Substring

Here’s a simple example that finds the position of a substring within a string:

JavaScript
// Original string
let str = 'Departed Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');
console.log(index);

[Example 2]: Using indexOf() to Locate Substrings

The indexOf() method can be used to search for longer substrings:

JavaScript
// JavaScript to illustrate indexOf() method

// Original string
let str = 'Departed Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('ed Tr');

console.log(index);

[Example 3]: Handling Case Sensitivity in indexOf() Method

The indexOf() method is case-sensitive. If the cases don’t match, the method will return -1:

JavaScript
// Original string
let str = 'Departed Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('train');

console.log(index);

You can specify a starting index from where the search begins. This is useful when you want to skip certain parts of the string:

JavaScript
// Original string
let str = 'Departed Train before another Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');

console.log(index);
Comment

Explore