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

0

2 Answers 2

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');
Sign up to request clarification or add additional context in comments.

2 Comments

we can add string.lowercase so that we get the character count with same character in either upper or lowercase
This one is faster than the one of Amit Joki.
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

4 Comments

Thanks for the answer. If I passed "abcdef", it should return 0, but it is showing an error message "TypeError: Cannot read property 'length' of null"
@NaveenKrishna now it should work.
Wow excellent man, it works! Simple and great answer.
@NaveenKrishna glad to have helped you. I answered this because it was kinda interesting. It would be better on your part to post your try in the question. Any glad to have helped :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.