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

后端 未结 30 2532
礼貌的吻别
礼貌的吻别 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:24

    I know this might be an old question but I have a simple solution for low-level beginners in JavaScript.

    As a beginner, I could only understand some of the solutions to this question so I used two nested FOR loops to check each character against every other character in the string, incrementing a count variable for each character found that equals that character.

    I created a new blank object where each property key is a character and the value is how many times each character appeared in the string(count).

    Example function:-

    function countAllCharacters(str) {
      var obj = {};
      if(str.length!==0){
        for(i=0;i

提交回复
热议问题