1var temp = "This is a string.";
2var count = (temp.match(/is/g) || []).length;
3console.log(count);
4
5Output: 2
6
7Explaination : The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches 'is' twice.
1function count (string) {
2 var count = {};
3 string.split('').forEach(function(s) {
4 count[s] ? count[s]++ : count[s] = 1;
5 });
6 return count;
7}
1let counter = str => {
2 return str.split('').reduce((total, letter) => {
3 total[letter] ? total[letter]++ : total[letter] = 1;
4 return total;
5 }, {});
6};
7
8counter("aabsssd"); // => { a: 2, b: 1, s: 3, d: 1 }