String.indexOf()
Finds the first index of a substring, or -1 if not found.
string.indexOf(searchValue, fromIndex?)This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Finds the first index of a substring, or -1 if not found.
The indexOf() method performs a case-sensitive search to find the first occurrence of a substring within a string. It returns the index of the first character of the first match, or -1 if the value is not found. If the searchValue is an empty string, it returns the value of fromIndex (clamped between 0 and the string length). Under the hood, modern engines optimize this search; however, it remains an O(N*M) operation in the worst case. Unlike includes(), which returns a boolean, indexOf() is useful when the specific position of the data is required for subsequent operations like slicing. Note that non-string inputs are implicitly coerced to strings, which can lead to unexpected results if null or undefined are passed. For example, passing null will search for the literal string 'null'.
Quick reference
Syntax
string.indexOf(searchValue, fromIndex?)
Inputs
Parameters
See it in practice
Examples
Basic Substring Search
var phrase = 'The quick brown fox';
console.log(phrase.indexOf('quick'));4
Locates the start of the word 'quick' in the string.
Using the Starting Offset
var text = 'To be, or not to be';
var first = text.indexOf('be');
var second = text.indexOf('be', first + 1);
console.log(second);16
Finds the second occurrence of 'be' by starting the search after the first match.
Searching with Type Coercion
var digits = '0123456789';
console.log(digits.indexOf(5));5
The number 5 is coerced to the string '5' before the search is performed.
Debug faster
Common Errors
LogicError
Cause: Using indexOf() directly in an 'if' statement to check for existence. If the substring is at index 0, the condition evaluates to 0 (falsy), incorrectly suggesting the string was not found.
Fix: Always compare the return value to -1.
var s = 'Hello'; if (s.indexOf('H')) { /* this block won't run because 0 is falsy */ }LogicError
Cause: Assuming the search is case-insensitive.
Fix: Normalize the case of both strings using toLowerCase() or toUpperCase() before calling indexOf().
var s = 'JavaScript'; console.log(s.indexOf('script')); // returns -1Runtime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Finds the first index of a substring, or -1 if not found.
searchValue: Substring to search for. fromIndex: Index to start searching from.
LogicError: Always compare the return value to -1. LogicError: Normalize the case of both strings using toLowerCase() or toUpperCase() before calling indexOf().