JavaScript - Index position of a word within a string
JavaScript Searching Algorithm: Exercise-1 with Solution
Find Word Index Positions
Write a JavaScript program to find all the index positions of a given word within a given string.
Test Data:
( "The quick brown fox jumps over the lazy dog.", "the") -> [31]
( "the quick brown fox jumps over the lazy dog.", "the") -> [0, 31]
( "the quick brown fox jumps over the lazy dog.", "cat") -> []
Sample Solution:
JavaScript Code:
Sample Output:
[31] [0,31] []
Flowchart:


Live Demo:
* To run the code mouse over on Result panel and click on 'RERUN' button.*
For more Practice: Solve these Related Problems:
- Write a JavaScript function that returns an array of all starting indices where a given word occurs in a string, ignoring case.
- Write a JavaScript function that finds all overlapping occurrences of a word in a string and returns their index positions.
- Write a JavaScript function that strips punctuation from a string before searching for the index positions of a given word.
- Write a JavaScript function that accepts a regular expression as the search criterion and returns the starting indices of all matches in a string.
Improve this sample solution and post your code through Disqus
Previous: JavaScript Searching Algorithm Exercises Home.
Next: Linear search algorithm.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.