Counts the occurrences of a substring in a given string.
Array.prototype.indexOf()
to look for searchValue
in str
.i
.while
loop that will return as soon as the value returned from Array.prototype.indexOf()
is -1
.const countSubstrings = (str, searchValue) => {
let count = 0,
i = 0;
while (true) {
const r = str.indexOf(searchValue, i);
if (r !== -1) [count, i] = [count + 1, r + 1];
else return count;
}
};
countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3
countSubstrings('tutut tut tut', 'tut'); // 4
JavaScript, String
Finds all the indexes of a substring in a given string.
JavaScript, String
Replaces the last occurrence of a pattern in a string.
JavaScript, String
Creates a new string with the results of calling a provided function on every character in the given string.