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

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

    I made a slight improvement on the accepted answer, it allows to check with case-sensitive/case-insensitive matching, and is a method attached to the string object:

    String.prototype.count = function(lit, cis) {
        var m = this.toString().match(new RegExp(lit, ((cis) ? "gi" : "g")));
        return (m != null) ? m.length : 0;
    }
    

    lit is the string to search for ( such as 'ex' ), and cis is case-insensitivity, defaulted to false, it will allow for choice of case insensitive matches.


    To search the string 'I love StackOverflow.com' for the lower-case letter 'o', you would use:

    var amount_of_os = 'I love StackOverflow.com'.count('o');
    

    amount_of_os would be equal to 2.


    If we were to search the same string again using case-insensitive matching, you would use:

    var amount_of_os = 'I love StackOverflow.com'.count('o', true);
    

    This time, amount_of_os would be equal to 3, since the capital O from the string gets included in the search.

提交回复
热议问题