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

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

    ok, an other one with regexp - probably not fast, but short and better readable then others, in my case just '_' to count

    key.replace(/[^_]/g,'').length
    

    just remove everything that does not look like your char but it does not look nice with a string as input

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

    I believe you will find the below solution to be very short, very fast, able to work with very long strings, able to support multiple character searches, error proof, and able to handle empty string searches.

    function substring_count(source_str, search_str, index) {
        source_str += "", search_str += "";
        var count = -1, index_inc = Math.max(search_str.length, 1);
        index = (+index || 0) - index_inc;
        do {
            ++count;
            index = source_str.indexOf(search_str, index + index_inc);
        } while (~index);
        return count;
    }
    

    Example usage:

    console.log(substring_count("Lorem ipsum dolar un sit amet.", "m "))
    
    function substring_count(source_str, search_str, index) {
        source_str += "", search_str += "";
        var count = -1, index_inc = Math.max(search_str.length, 1);
        index = (+index || 0) - index_inc;
        do {
            ++count;
            index = source_str.indexOf(search_str, index + index_inc);
        } while (~index);
        return count;
    }

    The above code fixes the major performance bug in Jakub Wawszczyk's that the code keeps on looks for a match even after indexOf says there is none and his version itself is not working because he forgot to give the function input parameters.

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

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

    My solution with ramda js:

    const testString = 'somestringtotest'
    
    const countLetters = R.compose(
      R.map(R.length),
      R.groupBy(R.identity),
      R.split('')
    )
    
    countLetters(testString)
    

    Link to REPL.

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

    The function takes string str as parameter and counts occurrence of each unique characters in the string. The result comes in key - value pair for each character.

    var charFoundMap = {};//object defined
        for (var i = 0; i < str.length; i++) {
    
           if(!charFoundMap[ str[i] ])  {
            charFoundMap[ str[i] ]=1;
           } 
           else
           charFoundMap[ str[i] ] +=1;
           //if object does not contain this 
        }
        return charFoundMap;
    
    } 
    
    0 讨论(0)
  • 2020-11-22 03:12

    What about string.split(desiredCharecter).length-1

    Example:

    var str = "hellow how is life"; var len = str.split("h").length-1; will give count 2 for character "h" in the above string;

    0 讨论(0)
提交回复
热议问题