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

后端 未结 30 2540
礼貌的吻别
礼貌的吻别 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
    闹比i (楼主)
    2020-11-22 02:58

    Simply, use the split to find out the number of occurrences of a character in a string.

    mainStr.split(',').length // gives 4 which is the number of strings after splitting using delimiter comma

    mainStr.split(',').length - 1 // gives 3 which is the count of comma

提交回复
热议问题