返回给定字符串中元音的数量


DESCRIPTION

Return the number (count) of vowels in the given string.

We will consider a, e, i, o, u as vowels for this Kata (but not y).

The input string will only consist of lower case letters and/or spaces.

SOLUTION

  • 方法一:数组的 includes() 方法
1
2
3
4
5
6
7
8
9
10
function getCount(str) {
let count = 0;
let strArray = str.split("");
strArray.forEach((item) => {
if (["a", "e", "i", "o", "u"].includes(item)) {
count++;
}
});
return count;
}
  • 方法二:利用正则表达式
1
2
3
function getCount(str) {
return (str.match(/[aeiou]/gi) || []).length;
}
  • 方法三:filter() 方法
1
2
3
function getCount(str) {
return str.split("").filter((c) => "aeiouAEIOU".includes(c)).length;
}

Reference

Vowel Count