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

后端 未结 30 2498
礼貌的吻别
礼貌的吻别 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 02:58

    There are at least four ways. The best option, which should also be the fastest -owing to the native RegEx engine -, is placed at the top. jsperf.com is currently down, otherwise I would provide you with performance statistics.

    Update: Please, find the performance tests here, and run them yourselves, so as to contribute your performance results. The specifics of the results will be given later.

    1.

     ("this is foo bar".match(/o/g)||[]).length
     //>2
    

    2.

    "this is foo bar".split("o").length-1
     //>2
    

    split not recommended. Resource hungry. Allocates new instances of 'Array' for each match. Don't try that for a >100MB file via FileReader. You can actually easily observe the EXACT resource usage using Chrome's profiler option.

    3.

    var stringsearch = "o"
       ,str = "this is foo bar";
    for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) );
     //>count:2
    

    4.

    searching for a single character

    var stringsearch = "o"
       ,str = "this is foo bar";
    for(var i=count=0; icount:2
    

    Update:

    5.

    element mapping and filtering, not recommended due to its overall resource preallocation rather than using Pythonian 'generators'

    var str = "this is foo bar"
    str.split('').map( function(e,i){ if(e === 'o') return i;} )
                 .filter(Boolean)
    //>[9, 10]
    [9, 10].length
    //>2
    

    Share: I made this gist, with currently 8 methods of character-counting, so we can directly pool and share our ideas - just for fun, and perhaps some interesting benchmarks :)

    https://gist.github.com/2757250

提交回复
热议问题