JavaScript程序计算字符串中的元音数量
要理解这个示例,你应该了解以下JavaScript编程主题的知识:
五个字母 a, e, i, o 和 u 被称为元音字母。除这5个元音外的其他字母被称为辅音。
示例1:使用正则表达式计算元音字母的数量
// 程序:计算字符串中元音字母的数量
function countVowel(str) {
// 查找元音的数量
const count = str.match(/[aeiou]/gi).length;
// 返回元音数量
return count;
}
// 输入
const string = prompt("输入一个字符串:");
const result = countVowel(string);
console.log(result);
输出
输入一个字符串:JavaScript程序
5
在上述程序中,提示用户输入一个字符串,并将该字符串传递给countVowel()
函数。
- 使用正则表达式(RegEx)模式结合
match()
方法来找出字符串中的元音数量。 - 模式
/[aeiou]/gi
检查字符串中所有的元音(不区分大小写)。例如,str.match(/[aeiou]/gi);
得到 ["a", "a", "i", "o", "a"] length
属性给出了存在的元音数量。
示例2:使用for循环计算元音字母的数量
// 程序:计算字符串中元音字母的数量
// 定义元音
const vowels = ["a", "e", "i", "o", "u"];
function countVowel(str) {
// 初始化计数
let count = 0;
// 遍历字符串,测试每个字符是否为元音
for (let letter of str.toLowerCase()) {
if (vowels.includes(letter)) {
count++;
}
}
// 返回元音数量
return count;
}
// 输入
const string = prompt("输入一个字符串:");
const result = countVowel(string);
console.log(result);
输出
输入一个字符串:JavaScript程序
5
在上面的示例中,
- 所有的元音字母存储在一个
vowels
数组中。 - 最初,
count
变量的值是0。 - 使用
for...of
循环遍历字符串的所有字符。 toLowerCase()
方法将字符串的所有字符转换为小写。includes()
方法检查vowels
数组中是否包 含字符串的任何字符。- 如果有任何字符匹配,
count
的值增加1。