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
-1The last match
lastIndexOf() searches from the end:
console.log('hello world'.lastIndexOf('o'));Output:
7All 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, 5With a regular expression
search() works like indexOf(), but takes a pattern:
console.log('Room 42'.search(/\d/));Output:
5Common 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
foundFunctions used in this recipe
- String.prototype.indexOf — Finds the position of the first occurrence of a substring.
- String.prototype.lastIndexOf — Finds the last occurrence of a text in a string.
- String.prototype.search — Returns the position of the first regex match.