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

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

    My solution:

    function countOcurrences(str, value){
       var regExp = new RegExp(value, "gi");
       return str.match(regExp) ? str.match(regExp).length : 0;  
    }
    
    0 讨论(0)
  • 2020-11-22 03:04

    Performance of Split vs RegExp

    var i = 0;
    
    var split_start = new Date().getTime();
    while (i < 30000) {
      "1234,453,123,324".split(",").length -1;
      i++;
    }
    var split_end = new Date().getTime();
    var split_time = split_end - split_start;
    
    
    i= 0;
    var reg_start = new Date().getTime();
    while (i < 30000) {
      ("1234,453,123,324".match(/,/g) || []).length;
      i++;
    }
    var reg_end = new Date().getTime();
    var reg_time = reg_end - reg_start;
    
    alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");

    0 讨论(0)
  • 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;
      }
    }
    
    0 讨论(0)
  • 2020-11-22 03:05

    Easiest way i found out...

    Example-

    str = 'mississippi';
    
    function find_occurences(str, char_to_count){
        return str.split(char_to_count).length - 1;
    }
    
    find_occurences(str, 'i') //outputs 4
    
    0 讨论(0)
  • 2020-11-22 03:05

    And there is:

    function character_count(string, char, ptr = 0, count = 0) {
        while (ptr = string.indexOf(char, ptr) + 1) {count ++}
        return count
    }
    

    Works with integers too!

    0 讨论(0)
  • 2020-11-22 03:06

    You can also rest your string and work with it like an array of elements using

    • Array.prototype.filter()

    const mainStr = 'str1,str2,str3,str4';
    const commas = [...mainStr].filter(l => l === ',').length;
    
    console.log(commas);

    Or

    • Array.prototype.reduce()

    const mainStr = 'str1,str2,str3,str4';
    const commas = [...mainStr].reduce((a, c) => c === ',' ? ++a : a, 0);
    
    console.log(commas);

    0 讨论(0)
提交回复
热议问题