Counting number of vowels in a string with JavaScript

前端 未结 18 1639
旧巷少年郎
旧巷少年郎 2020-12-08 23:53

I\'m using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes()

18条回答
  •  孤城傲影
    2020-12-09 00:23

    As the introduction of forEach in ES5 this could be achieved in a functional approach, in a more compact way, and also have the count for each vowel and store that count in an Object.

    function vowelCount(str){
      let splitString=str.split('');
      let obj={};
      let vowels="aeiou";
      splitString.forEach((letter)=>{
        if(vowels.indexOf(letter.toLowerCase())!==-1){
          if(letter in obj){
            obj[letter]++;
          }else{
            obj[letter]=1;
          }
        }   
    
     });
     return obj;    
    }
    

提交回复
热议问题