Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 26, 2021 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/aeb99b1cc89ab3a09ee15e2a1d5058a9 to your computer and use it in GitHub Desktop.
Save yavgel85/aeb99b1cc89ab3a09ee15e2a1d5058a9 to your computer and use it in GitHub Desktop.
indexOfSubstrings #js #algorithm
// Finds all the indexes of a substring in a given string.
// Use Array.prototype.indexOf() to look for searchValue in str.
// Use yield to return the index if the value is found and update the index, i.
// Use a while loop that will terminate the generator as soon as the value returned from Array.prototype.indexOf() is -1.
const indexOfSubstrings = function* (str, searchValue) {
let i = 0;
while (true) {
const r = str.indexOf(searchValue, i);
if (r !== -1) {
yield r;
i = r + 1;
} else return;
}
};
// Examples
[...indexOfSubstrings('tiktok tok tok tik tok tik', 'tik')]; // [0, 15, 23]
[...indexOfSubstrings('tutut tut tut', 'tut')]; // [0, 2, 6, 10]
[...indexOfSubstrings('hello', 'hi')]; // []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment