Counting number of vowels in a string with JavaScript

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

    You can convert the given string into an array using the spread operator, and then you can filter() the characters to only those which are vowels (case-insensitive).

    Afterwards, you can check the length of the array to obtain the total number of vowels in the string:

    const vowel_count = string => [...string].filter(c => 'aeiou'.includes(c.toLowerCase())).length;
    
    console.log(vowel_count('aaaa'));            // 4
    console.log(vowel_count('AAAA'));            // 4
    console.log(vowel_count('foo BAR baz QUX')); // 5
    console.log(vowel_count('Hello, world!'));   // 3

提交回复
热议问题