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

后端 未结 30 2536
礼貌的吻别
礼貌的吻别 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条回答
  •  梦毁少年i
    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

提交回复
热议问题