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

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

    I have found that the best approach to search for a character in a very large string (that is 1 000 000 characters long, for example) is to use the replace() method.

    window.count_replace = function (str, schar) {
        return str.length - str.replace(RegExp(schar), '').length;
    };
    

    You can see yet another JSPerf suite to test this method along with other methods of finding a character in a string.

提交回复
热议问题