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

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

    Here's one just as fast as the split() and the replace methods, which are a tiny bit faster than the regex method (in Chrome and Firefox both).

    let num = 0;
    let str = "str1,str2,str3,str4";
    //Note: Pre-calculating `.length` is an optimization;
    //otherwise, it recalculates it every loop iteration.
    let len = str.length;
    //Note: Don't use a `for (... of ...)` loop, it's slow!
    for (let charIndex = 0; charIndex < len; ++charIndex) {
      if (str[charIndex] === ',') {
        ++num;
      }
    }
    

提交回复
热议问题