indexOf and lastIndexOf String Methods
indexOf() searches a string from the start and returns the position of the first match. lastIndexOf() searches from the end and returns the position of the last match. Both return -1 when there is no match, and both compare text exactly, so the search is case-sensitive.
Finding the first and last match
Section titled “Finding the first and last match”Positions start at 0. The position returned is where the match begins.
const sentence = 'The cat sat on the mat';
console.log(sentence.indexOf('at'));console.log(sentence.lastIndexOf('at'));console.log(sentence.indexOf('dog'));console.log(sentence.indexOf('the'));console.log(sentence.toLowerCase().indexOf('the'));This prints:
520-1150indexOf('the') skips the capitalised The at the start. Lower-casing the string first makes the search ignore case.
Starting part-way through
Section titled “Starting part-way through”Both methods take a second argument, which is the position to search from. indexOf() searches forwards from it, and lastIndexOf() searches backwards from it. Together with slice(), this is enough to pull a piece out of a string.
const path = 'docs/2026/december/report.txt';
console.log(path.indexOf('/'));console.log(path.indexOf('/', 5));console.log(path.lastIndexOf('/'));console.log(path.lastIndexOf('/', 10));console.log(path.slice(path.lastIndexOf('/') + 1));This prints:
49189report.txtFinding every match
Section titled “Finding every match”Feeding each match’s position, plus one, back in as the starting point walks through the string until indexOf() returns -1.
const todo = 'buy milk, post letter, buy bread, buy stamps';const positions = [];
let position = todo.indexOf('buy');while (position !== -1) { positions.push(position); position = todo.indexOf('buy', position + 1);}console.log(positions);This prints:
[ 0, 23, 34 ]For patterns rather than fixed text, matchAll() with a regular expression does the same job, and it is covered in startsWith, endsWith and finding strings.
Testing for a match
Section titled “Testing for a match”A common mistake is to use the result of indexOf() directly as a condition. A match at position 0 is falsy, so it looks like no match. Compare with -1, or use includes(), which returns a Boolean.
const tags = 'urgent,home';
if (tags.indexOf('urgent')) { console.log('found');} else { console.log('not found');}console.log(tags.indexOf('urgent') !== -1);console.log(tags.includes('urgent'));console.log(tags.indexOf(''), tags.lastIndexOf(''));This prints:
not foundtruetrue0 11The last line shows that an empty search string always matches, at the start for indexOf() and at the end for lastIndexOf(). Code that searches for text typed by a user should check for an empty string first.
Arrays have indexOf() and lastIndexOf() methods too, which work the same way on elements; see strings as arrays.
Steve Griffith covers this topic in his video indexOf and lastIndexOf String Methods.