xxxxxxxxxx
// count occurrences in string s1 letter a
let s1="aaabccddd";
let count1=(s1.match(/a/g)||[]).length;
console.log(count1);
// answer 3
xxxxxxxxxx
function countOccurences(string, word) {
return string.split(word).length - 1;
}
var text="We went down to the stall, then down to the river.";
var count=countOccurences(text,"down"); // 2
xxxxxxxxxx
// No Regex Version (With Overlapping)
// str => input string
// sub => input substring
// returns number of occurrences of sub in str with overlaping
const countOccurrences = (str, sub) => {
let count = 0;
pos = str.indexOf(sub);
while(pos>=0){
count++;
pos++;
pos = str.indexOf(sub, pos)
}
return count;
}