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

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

    A quick Google search got this (from http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript)

    String.prototype.count=function(s1) { 
        return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
    }
    

    Use it like this:

    test = 'one,two,three,four'
    commas = test.count(',') // returns 3
    

提交回复
热议问题