.indexOf()

mehboobali98's avatar
Published Jun 23, 2021Updated Jun 28, 2023
Contribute to Docs

Searches a string for a given value and returns the first index if found. Returns -1 if not found.

Syntax

string.indexOf(value, startSearch);
  • value is the value to search for in a string.
  • startSearch (optional), indicates the index to start the search at.

Examples

Find the index of string:

const gingerbreadRhyme = `You can't catch me! I'm the Gingerbread Man!`;
const captureGingerbreadMan = gingerbreadRhyme.indexOf('Gingerbread Man');
console.log(captureGingerbreadMan);
// Output: 28

Find the first occurrence of a string:

const baseballChant =
'Hey batter, batter, batter, batter, batter! Swing, batter!';
const firstBatter = baseballChant.indexOf('batter');
console.log(firstBatter);
// Output: 4

Use second parameter to start search later in string:

const baseballChant =
'Hey batter, batter, batter, batter, batter! Swing, batter!';
const latterBatter = baseballChant.indexOf('batter', 18);
console.log(latterBatter);
// Output: 20

Return -1 if not found:

const people = ['Dominic', 'Marshawn', 'Alexis', 'Shannon'];
const didYouFindWaldo = people.indexOf('Waldo');
console.log(didYouFindWaldo);
// Output: -1

Codebyte Example

The following is runnable, and demonstrates the use of the .indexOf() method:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy