Count the number of occurrences of a character in a string in Javascript

后端 未结 30 2535
礼貌的吻别
礼貌的吻别 2020-11-22 02:33

I need to count the number of occurrences of a character in a string.

For example, suppose my string contains:

var mainStr = \"str1,str2,str3,str4\";         


        
30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:11

    The function takes string str as parameter and counts occurrence of each unique characters in the string. The result comes in key - value pair for each character.

    var charFoundMap = {};//object defined
        for (var i = 0; i < str.length; i++) {
    
           if(!charFoundMap[ str[i] ])  {
            charFoundMap[ str[i] ]=1;
           } 
           else
           charFoundMap[ str[i] ] +=1;
           //if object does not contain this 
        }
        return charFoundMap;
    
    } 
    

提交回复
热议问题