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.
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 : Finding the First Occurrence of a Substring
Here’s a simple example that finds the position of a substring within a string:
// Original string
let str = 'Departed Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');
console.log(index);
Example : Using indexOf() to Locate Substrings
The indexOf() method can be used to search for longer substrings:
// 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 : Handling Case Sensitivity in indexOf() Method
The indexOf() method is case-sensitive. If the cases don’t match, the method will return -1:
// Original string
let str = 'Departed Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('train');
console.log(index);
Example : Using an Index to Start the Search
You can specify a starting index from where the search begins. This is useful when you want to skip certain parts of the string:
// Original string
let str = 'Departed Train before another Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');
console.log(index);
Supported browsers
- Chrome 1
- Edge 12
- Firefox 1
- Opera 3
- Safari 1