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

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

    My solution:

    function countOcurrences(str, value){
       var regExp = new RegExp(value, "gi");
       return str.match(regExp) ? str.match(regExp).length : 0;  
    }
    

提交回复
热议问题