Count number of occurrences for each char in a string

后端 未结 11 2346
挽巷
挽巷 2020-12-16 17:42

I want to count the number of occurrences of each character in a given string using JavaScript.

For example:

var str = \"I want to count the number         


        
11条回答
  •  星月不相逢
    2020-12-16 18:07

    This worked well for me :

        function Char_Count(str1) {
        var chars = {};
        str1.replace(/\S/g, function(l){chars[l] = (isNaN(chars[l]) ? 1 : 
        chars[l] + 1);});
        return chars;
      }
    
      var myString = "This is my String";
      console.log(Char_Count(myString));
    

提交回复
热议问题