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

后端 未结 30 2917
礼貌的吻别
礼貌的吻别 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 02:58

    Here is my solution. Lots of solution already posted before me. But I love to share my view here.

    const mainStr = 'str1,str2,str3,str4';
    
    const commaAndStringCounter = (str) => {
      const commas = [...str].filter(letter => letter === ',').length;
      const numOfStr = str.split(',').length;
    
      return `Commas: ${commas}, String: ${numOfStr}`;
    }
    
    // Run the code
    console.log(commaAndStringCounter(mainStr)); // Output: Commas: 3, String: 4
    

    Here you find my REPL

提交回复
热议问题