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

后端 未结 30 3213
礼貌的吻别
礼貌的吻别 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 02:59

    Here is a similar solution, but it uses Array.prototype.reduce

    function countCharacters(char, string) {
      return string.split('').reduce((acc, ch) => ch === char ? acc + 1: acc, 0)
    }
    

    As was mentioned, String.prototype.split works much faster than String.prototype.replace.

提交回复
热议问题