Find the position of a word with indexOf in JavaScript
Beginner · 4 min read
"Where in this text is the word I'm looking for?" is a question you ask whenever you highlight a search result, cut a string at a marker, or check whether a sentence mentions something. JavaScript answers it with indexOf, which searches from the front, and lastIndexOf, which searches from the back.
In this tutorial you will find the first and last position of 'the' in a sentence, learn what you get when the word isn't there, and avoid the classic bug where a match at the very start looks like "not found". You only need to know that characters in a string are numbered from 0.
What indexOf gives back
indexOf doesn't return the word. It returns a number: the position where the match starts. Here is our sentence with some positions marked:
the cat sat on the mat
0 4 8 15
The first 'the' starts at 0. The second starts at 15.
The "not found" signal
When there is no match, you don't get undefined or false. You get -1. A real position can never be negative, so -1 safely means "not here".
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
8 Find where something is
easyFind the first and last position of 'the' in a sentence, and say what happens when it is not there.
Stuck? Three hints, smallest first
- 1.
indexOfsearches forwards,lastIndexOfbackwards. - 2. Both return
-1when there is no match, neverundefined. - 3. Both take a second argument saying where to start.
Step 1: the first and last match
const line = 'the cat sat on the mat';
console.log(line.indexOf('the')); // 0
console.log(line.lastIndexOf('the')); // 15
indexOf starts at the front and stops at the first match. lastIndexOf starts at the back and stops at the first match it meets coming the other way. Both report where the match starts.
Step 2: search for something missing
const line = 'the cat sat on the mat';
console.log(line.indexOf('dog')); // -1
console.log(line.indexOf('The')); // -1
'dog' isn't there, so the answer is -1. 'The' with a capital T isn't there either: the search is case sensitive, which means upper and lower case letters count as different characters.
Step 3: start the search further along
Both methods take a second number: where to begin.
const line = 'the cat sat on the mat';
console.log(line.indexOf('the', 1)); // 15
console.log(line.lastIndexOf('the', 14)); // 0
indexOf('the', 1) begins at position 1, so it skips the match at 0 and finds the one at 15. This is how you walk through every match: search again from just after the last one you found.
For lastIndexOf the second number means "the match may not start after this position". The second 'the' starts at 15, which is after 14, so it is ruled out, and you get 0.
Step 4: the empty string
What if you search for nothing at all?
console.log('the cat'.indexOf('')); // 0
console.log('abc'.lastIndexOf('')); // 3
An empty string fits anywhere, so indexOf finds it at the very first spot, 0. lastIndexOf finds it at the very last spot, which is the length of the string. Keep this in mind if the word you search for comes from a user: an empty search box "matches" everything.
Step 5: the classic mistake
Here is a check that looks right:
const line = 'the cat sat on the mat';
if (line.indexOf('the')) {
console.log('found it');
} else {
console.log('not found'); // this is what runs
}
It prints 'not found', even though 'the' is the very first word. An if treats certain values as false, and 0 is one of them. The match is at position 0, so the if reads it as "no".
const line = 'the cat sat on the mat';
console.log(Boolean(line.indexOf('the'))); // false
console.log(line.indexOf('the') !== -1); // true
console.log(line.indexOf('cat') !== -1); // true
Boolean(...) shows what an if would see. The fix is to compare with -1 directly: "is the position anything other than -1?"
Step 6: when you only need yes or no
If you don't need the position, there is a simpler method that avoids the trap entirely:
const line = 'the cat sat on the mat';
console.log(line.includes('the')); // true
console.log(line.includes('dog')); // false
includes returns true or false. Use indexOf when you need to know where, and includes when you only need to know whether.
The full solution
Here is the complete answer, with the first and last match, the missing word, and a line that spells out the classic mistake. Press Run, then read the last two checks.
const line = 'the cat sat on the mat';
console.log('indexOf("the") :', line.indexOf('the'));
console.log('lastIndexOf("the") :', line.lastIndexOf('the'));
console.log('indexOf("dog") :', line.indexOf('dog'));
console.log('--- the classic mistake ---');
console.log('if (line.indexOf("the")) would be FALSE, because the answer is 0');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first "the" is at index 0', line.indexOf('the'), 0);
test('the last one is at index 15', line.lastIndexOf('the'), 15);
test('a missing needle gives -1, not undefined', line.indexOf('dog'), -1);
test('a start position skips the first hit', line.indexOf('the', 1), 15);
test('lastIndexOf searches backwards from its start position', line.lastIndexOf('the', 14), 0);
test('the search is case sensitive', line.indexOf('The'), -1);
test('an empty needle is found at 0', line.indexOf(''), 0);
test('and at the length when searching backwards', 'abc'.lastIndexOf(''), 3);
test('so compare against -1 rather than testing truthiness', line.indexOf('cat') !== -1, true);
test('because index 0 is FALSY and would read as "not found"', Boolean(line.indexOf('the')), false);
The last assertion is the reason includes was added to the language. if (line.indexOf('the')) is false when the match is at the very start, which is the one position a careless test gets wrong and the one position a test string is most likely to use.
lastIndexOf's second argument is not "search from here to the end" but "the match may not start after here", which is why lastIndexOf('the', 14) returns 0 rather than 15.
Common mistakes
- Writing
if (text.indexOf(word)). A match at position 0 counts as false. Compare with!== -1, or useincludes. - Expecting
undefinedorfalsewhen nothing is found.indexOfalways returns a number, and "not found" is-1. - Forgetting the search is case sensitive. Lower-case both sides first if case shouldn't matter:
text.toLowerCase().indexOf('the').
Try it yourself
- Write
countMatches(text, word)that usesindexOfwith a start position in a loop to count how many times'the'appears. - Use
indexOfandsliceto get everything after the first space in'Ada Lovelace'. - Use
lastIndexOf('.')to get the extension of'photo.final.jpg'.