五个字母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
在上面的程序中,提示用户输入一个字符串并将该字符串传递给
正则表达式(RegEx) 模式与 countVowel()
函数。
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。