字母 a、e、i、o 和 u 称为元音字母。除这 5 个元音字母外的所有其他字母都称为辅音字母。
示例 1:使用正则表达式计算元音字母的数量
// program to count the number of vowels in a string
function countVowel(str) {
// find the count of vowels
const count = str.match(/[aeiou]/gi).length;
// return number of vowels
return count;
}
// take input
const string = prompt('Enter a string: ');
const result = countVowel(string);
console.log(result);
输出
Enter a string: JavaScript program 5
在上面的程序中,会提示用户输入一个字符串,该字符串被传递给 countVowel()
函数。
- 正则表达式(RegEx)模式与
match()
方法一起使用,以查找字符串中元音字母的数量。 - 模式
/[aeiou]/gi
用于检查字符串中的所有元音字母(不区分大小写)。这里,
str.match(/[aeiou]/gi);
返回 ["a", "a", "i", "o", "a"] length
属性给出存在的元音字母的数量。
示例 2:使用 for 循环计算元音字母的数量
// program to count the number of vowels in a string
// defining vowels
const vowels = ["a", "e", "i", "o", "u"]
function countVowel(str) {
// initialize count
let count = 0;
// loop through string to test if each character is a vowel
for (let letter of str.toLowerCase()) {
if (vowels.includes(letter)) {
count++;
}
}
// return number of vowels
return count
}
// take input
const string = prompt('Enter a string: ');
const result = countVowel(string);
console.log(result);
输出
Enter a string: JavaScript program 5
在上面的例子中:
- 所有元音字母都存储在
vowels
数组中。 - 最初,
count
变量的值为 0。 - 使用 for...of 循环遍历字符串的所有字符。
toLowerCase()
方法将字符串的所有字符转换为小写。includes()
方法检查vowel
数组是否包含字符串中的任何字符。- 如果任何字符匹配,
count
的值将增加 1。
另请阅读