Skip to content
Advertisement

indexOf to find all occurrences of a word in a String

I’m trying to use indexOf to find all occurrences of the characters ‘the’ in a sentence. For example, if the sentence were “The other day I went over there”, it should return 3.

I am able to do this up to the point where it finds the first index, but I’m unsure of how to write the loop. I originally had a for loop that searched the entire string, but it was returning the full string character length, instead of the occurrences of my specified character. How can I write a loop that will find all of the occurrences of the word? Thank you.

JavaScript

Advertisement

Answer

You can keep track of the index:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement