Finds all the indexes of a substring in a given string.
Array.prototype.indexOf()
to look for searchValue
in str
.yield
to return the index if the value is found and update the index, i
.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;
}
};
[...indexOfSubstrings('tiktok tok tok tik tok tik', 'tik')]; // [0, 15, 23]
[...indexOfSubstrings('tutut tut tut', 'tut')]; // [0, 2, 6, 10]
[...indexOfSubstrings('hello', 'hi')]; // []
Snippet collection
JavaScript generator functions are a more advanced yet very powerful JavaScript ES6 feature, which you can start using in your code right now.
JavaScript, String
Counts the occurrences of a substring in a given string.
JavaScript, String
Generates all left substrings of a given string.
JavaScript, String
Generates all right substrings of a given string.