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

后端 未结 30 2523
礼貌的吻别
礼貌的吻别 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:16
    s = 'dir/dir/dir/dir/'
    for(i=l=0;i<s.length;i++)
    if(s[i] == '/')
    l++
    
    0 讨论(0)
  • 2020-11-22 03:16

    I was working on a small project that required a sub-string counter. Searching for the wrong phrases provided me with no results, however after writing my own implementation I have stumbled upon this question. Anyway, here is my way, it is probably slower than most here but might be helpful to someone:

    function count_letters() {
    var counter = 0;
    
    for (var i = 0; i < input.length; i++) {
        var index_of_sub = input.indexOf(input_letter, i);
    
        if (index_of_sub > -1) {
            counter++;
            i = index_of_sub;
        }
    }
    

    http://jsfiddle.net/5ZzHt/1/

    Please let me know if you find this implementation to fail or do not follow some standards! :)

    UPDATE You may want to substitute:

        for (var i = 0; i < input.length; i++) {
    

    With:

    for (var i = 0, input_length = input.length; i < input_length; i++) {
    

    Interesting read discussing the above: http://www.erichynds.com/blog/javascript-length-property-is-a-stored-value

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 03:17

    The fifth method in Leo Sauers answer fails, if the character is on the beginning of the string. e.g.

    var needle ='A',
      haystack = 'AbcAbcAbc';
    
    haystack.split('').map( function(e,i){ if(e === needle) return i;} )
      .filter(Boolean).length;
    

    will give 2 instead of 3, because the filter funtion Boolean gives false for 0.

    Other possible filter function:

    haystack.split('').map(function (e, i) {
      if (e === needle) return i;
    }).filter(function (item) {
      return !isNaN(item);
    }).length;
    
    0 讨论(0)
  • 2020-11-22 03:17
    var a = "acvbasbb";
    var b= {};
    for (let i=0;i<a.length;i++){
        if((a.match(new RegExp(a[i], "g"))).length > 1){
            b[a[i]]=(a.match(new RegExp(a[i], "g"))).length;
        }
    }
    console.log(b);
    

    In javascript you can use above code to get occurrence of a character in a string.

    0 讨论(0)
  • 2020-11-22 03:18

    If you are using lodash, the _.countBy method will do this:

    _.countBy("abcda")['a'] //2
    

    This method also work with array:

    _.countBy(['ab', 'cd', 'ab'])['ab'] //2
    
    0 讨论(0)
提交回复
热议问题