/*
Find all starting indices of a word inside a larger text.
This function uses String.indexOf in a loop. The method is efficient
and implemented in optimized native code inside JavaScript engines.
*/
function findAllOccurrences(text: string, word: string): number[] {
const indices: number[] = [];
// Searching for an empty word is meaningless
if (word.length === 0) {
return indices;
}
let index: number = text.indexOf(word); // First occurrence
while (index !== -1) {
indices.push(index); // Store the index
/*
Search again starting one character after the previous match.
This allows detection of overlapping matches.
*/
index = text.indexOf(word, index + 1);
}
return indices;
}
// Example usage
const text: string =
"the quick brown fox jumps over the lazy dog. the fox is clever.";
const word: string = "the";
console.log("Text:", text);
console.log(`Word: "${word}"\n`);
console.log("Occurrences at indices:");
for (const idx of findAllOccurrences(text, word)) {
const indexValue: number = idx;
console.log(indexValue);
}
/*
run:
Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"
Occurrences at indices:
0
31
45
*/