Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find the position of a substring

Short answer

indexOf() returns the position of the first match, counting from zero, or -1 if nothing is found:

const text = 'hello world';
 
console.log(text.indexOf('o'));
console.log(text.indexOf('x'));

Output:

4
-1

The last match

lastIndexOf() searches from the end:

console.log('hello world'.lastIndexOf('o'));

Output:

7

All positions

The second argument of indexOf() sets where to start searching. A loop finds every match:

const text = 'banana';
const positions = [];
let index = text.indexOf('a');
 
while (index !== -1) {
  positions.push(index);
  index = text.indexOf('a', index + 1);
}
 
console.log(positions.join(', '));

Output:

1, 3, 5

With a regular expression

search() works like indexOf(), but takes a pattern:

console.log('Room 42'.search(/\d/));

Output:

5

Common mistake

Position 0 is a valid result, but it is falsy. Always compare with -1:

const text = 'apple pie';
 
console.log(text.indexOf('apple') ? 'found' : 'not found');
console.log(text.indexOf('apple') !== -1 ? 'found' : 'not found');

Output:

not found
found

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.