indexOf()
ES3+Returns the index of the first occurrence of a specified value in a string.
Syntax
string.indexOf(searchValue, fromIndex)Parameters
searchValue string The value to search for
fromIndex number optionalPosition to start searching from
Return Value
The index of the first occurrence, or -1 if not found
Examples
const str = 'Hello World';
console.log(str.indexOf('o'));
console.log(str.indexOf('x')); 📌 When to Use
Use indexOf() when you need both to check for substring existence AND know its position. For simple existence checks, prefer includes(). Use indexOf() for parsing, extracting portions of strings, or finding multiple occurrences.
⚠️ Common Mistakes
Using indexOf() !== -1 for simple boolean checks when includes() is more readable and expresses intent better.
Forgetting that indexOf() returns -1 (not null, undefined, or false) when the substring is not found.
Not using the fromIndex parameter when searching for multiple occurrences, resulting in infinite loops or incorrect results.
✅ Best Practices
Use indexOf() when you need the position for subsequent operations like slice() or substring().
To find all occurrences, use a while loop with fromIndex: indexOf(search, lastIndex + 1).
Consider using search() with regex when you need case-insensitive matching or pattern-based searching.
⚡ Performance Notes
indexOf() uses an optimized string search algorithm in modern engines. For very long strings with many searches, building an index or using more specialized algorithms may be beneficial. The fromIndex parameter can significantly improve performance when searching for subsequent occurrences.
🌍 Real World Example
String Parsing and Extraction
indexOf() is essential for parsing strings to extract data, finding delimiters, and processing text formats like email addresses, URLs, or structured data.
// Parse email into username and domain
function parseEmail(email) {
const atIndex = email.indexOf('@');
if (atIndex === -1) {
return null;
}
return {
username: email.slice(0, atIndex),
domain: email.slice(atIndex + 1)
};
}
console.log(parseEmail('user@example.com'));
// { username: 'user', domain: 'example.com' }
// Find all occurrences of a substring
function findAllOccurrences(str, search) {
const positions = [];
let index = str.indexOf(search);
while (index !== -1) {
positions.push(index);
index = str.indexOf(search, index + 1);
}
return positions;
}
console.log(findAllOccurrences('banana', 'a')); // [1, 3, 5]
// Extract query string parameters
function getQueryParam(url, param) {
const queryStart = url.indexOf('?');
if (queryStart === -1) return null;
const query = url.slice(queryStart + 1);
const paramStart = query.indexOf(param + '=');
if (paramStart === -1) return null;
const valueStart = paramStart + param.length + 1;
const valueEnd = query.indexOf('&', valueStart);
return valueEnd === -1
? query.slice(valueStart)
: query.slice(valueStart, valueEnd);
}
console.log(getQueryParam('https://example.com?name=John&age=30', 'name'));
// 'John'