.indexOf()

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

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy

Contributors