Counting number of vowels in a string with JavaScript

前端 未结 18 1497
旧巷少年郎
旧巷少年郎 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:29

    Short and ES6, you can use the function count(str);

    const count = str => (str.match(/[aeiou]/gi) || []).length;
    
    0 讨论(0)
  • 2020-12-09 00:31
    function countVowels(subject) {
        return subject.match(/[aeiou]/gi).length;
    }
    

    You don't need to convert anything, Javascript's error handling is enough to hint you on such a simple function if it will be needed.

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

    Convert the string to an array using the Array.from() method, then use the Array.prototype.filter() method to filter the array to contain only vowels, and then the length property will contain the number of vowels.

    const countVowels = str => Array.from(str)
      .filter(letter => 'aeiou'.includes(letter)).length;
    
    console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
    console.log(countVowels('test')); // 1
    console.log(countVowels('ffffd')); // 0

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

    This is the shortest solution

     function getCount(str) {
     return (str.match(/[aeiou]/ig)||[]).length;
     }
    
    0 讨论(0)
  • 2020-12-09 00:34

    You can use the simple includes function, which returns true if the given array contains the given character, and false if not.

    Note: The includes() method is case sensitive. So before comparing a character convert it to lowercase to avoid missing all the possible cases.

    for (var i = 0; i <= string.length - 1; i++) {
      if ('aeiou'.includes(string[i].toLowerCase())) {
        vowelsCount += 1;
      }
    }
    
    0 讨论(0)
  • 2020-12-09 00:36

    Use match but be careful as it can return a null if no match is found

    const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length);
    
    0 讨论(0)
提交回复
热议问题