Counting number of vowels in a string with JavaScript

前端 未结 18 1495
旧巷少年郎
旧巷少年郎 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:16
        (A)   
         const countVowels = data => [...data.toLowerCase()].filter(char => 'aeiou'.includes(char)).length;
    
        (B)    
          const countVowels = data => data.toLowerCase().split('').filter(char => 'aeiou'.includes(char)).length;
    
        countVowels("Stackoverflow") // 4 
    
    0 讨论(0)
  • 2020-12-09 00:19

    Just use this function [for ES5] :

    function countVowels(str){
        return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;        
    }
    

    Will work like a charm

    0 讨论(0)
  • 2020-12-09 00:20

    The following works and is short:

     function countVowels(str) {
     return ( str = str.match(/[aeiou]/gi)) ? str.length : 0;
    }
    
    
    console.log(countVowels("abracadabra")); // 5
    console.log(countVowels(""));            // 0

    0 讨论(0)
  • 2020-12-09 00:21

    You can actually do this with a small regex:

    function getVowels(str) {
      var m = str.match(/[aeiou]/gi);
      return m === null ? 0 : m.length;
    }
    

    This just matches against the regex (g makes it search the whole string, i makes it case-insensitive) and returns the number of matches. We check for null incase there are no matches (ie no vowels), and return 0 in that case.

    0 讨论(0)
  • 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;    
    }
    
    0 讨论(0)
  • 2020-12-09 00:23
    Function vowels(str){
       let count=0;
       const checker=['a','e','i','o','u'];
       for (let char of str.toLowerCase){
          if (checker.includes(char)){
            count++;
          }
       return count;
    }
    
    
    Function vowels(str){
       const match = str.match(/[aeiou]/gi);
       return match ? match.length : 0 ;
    }
    
    0 讨论(0)
提交回复
热议问题