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

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

提交回复
热议问题