5

Can anyone help me to get the count of repeated characters in a given string in javascript.

For example,

"abccdef" -> 1 (Only "c" repeated)

"Indivisibilities" -> 2 ("i" and "s" repeated)

Thank You

Naveen Krishna
  • 715
  • 2
  • 6
  • 13

2 Answers2

18

You can use like this

function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
    var character = string.charAt(i);
    if (freq[character]) {
       freq[character]++;
    } else {
       freq[character] = 1;
    }
}

return freq;
};

getFrequency('Indivisibilities');
iamsuman
  • 1,413
  • 19
  • 32
17

This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.

We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join. We can then make use of the regex /(.)\1+/g which essentially means match a letter and subsequent letters if it's the same.

When we use String.match with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch to return 0 in case match returns null and results in TypeError.

function howManyRepeated(str){
   try{ return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
   catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2
Amit Joki
  • 58,320
  • 7
  • 77
  • 95