Last Updated : 30 Sep, 2024
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.
Syntaxstr.indexOf(searchValue , index);Parameters
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);
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:
JavaScript
// 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4