.indexOf()
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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours