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

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

提交回复
热议问题