.indexOf()
Published Jun 23, 2021Updated Sep 3, 2021
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
All contributors
- Anonymous contributorAnonymous contributor3077 contributions
- robgmerrill
- christian.dinh
- Anonymous contributor
Looking to contribute?
- 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.