811 B
811 B
title, type, tags, author, cover, dateModified
| title | type | tags | author | cover | dateModified | ||
|---|---|---|---|---|---|---|---|
| Count substrings of string | snippet |
|
chalarangelo | obelisk | 2021-01-08T00:23:44+02:00 |
Counts the occurrences of a substring in a given string.
- Use
Array.prototype.indexOf()to look forsearchValueinstr. - Increment a counter if the value is found and update the index,
i. - Use a
whileloop that will return as soon as the value returned fromArray.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