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

后端 未结 30 3126
礼貌的吻别
礼貌的吻别 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 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);

提交回复
热议问题