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

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

    I have updated this answer. I like the idea of using a match better, but it is slower:

    console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
    
    console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
    

    jsfiddle

    Use a regular expression literal if you know what you are searching for beforehand, if not you can use the RegExp constructor, and pass in the g flag as an argument.

    match returns null with no results thus the || []

    The original answer I made in 2009 is below. It creates an array unnecessarily, but using a split is faster (as of September 2014). I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.

    Old answer (from 2009):

    If you're looking for the commas:

    (mainStr.split(",").length - 1) //3
    

    If you're looking for the str

    (mainStr.split("str").length - 1) //4
    

    Both in @Lo's answer and in my own silly jsperf test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.

提交回复
热议问题