JavaScript .indexOf()

Anonymous contributor's avatar
Anonymous contributor
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.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

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

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours