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

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

    The fastest method seems to be via the index operator:

    function charOccurances (str, char)
    {
      for (var c = 0, i = 0, len = str.length; i < len; ++i)
      {
        if (str[i] == char)
        {
          ++c;
        }
      }
      return c;
    }
    
    console.log( charOccurances('example/path/script.js', '/') ); // 2

    Or as a prototype function:

    String.prototype.charOccurances = function (char)
    {
      for (var c = 0, i = 0, len = this.length; i < len; ++i)
      {
        if (this[i] == char)
        {
          ++c;
        }
      }
      return c;
    }
    
    console.log( 'example/path/script.js'.charOccurances('/') ); // 2

提交回复
热议问题