JavaScript String indexOf() Method
The indexOf() method in JavaScript is used to find the index of the first occurrence of a specified value within a string. The method returns a 0-based index, making it a fundamental JavaScript string manipulation way.
The JavaScript indexOf() method helps locate a substring within a string and returns its position. This method is case-sensitive, meaning that “Hello“.indexOf(“hello”) will return -1 due to the mismatch in the case.
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:
// Original string
let str = 'Departed Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');
console.log(index);
// Original string
let str = 'Departed Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');
console.log(index);
Output
9
Example 2: 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);
// 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);
Output
6
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:
// Original string
let str = 'Departed Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('train');
console.log(index);
// Original string
let str = 'Departed Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('train');
console.log(index);
Output
-1
Example 4: 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);
// Original string
let str = 'Departed Train before another Train';
// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');
console.log(index);
Output
9
Supported browsers
- Chrome 1
- Edge 12
- Firefox 1
- Opera 3
- Safari 1