JavaScript 如何统计字符串中的元音字母数量
本文的方法是使用JavaScript返回字符串中元音字母的数量。元音字母是表示以这种方式产生的声音的字母:英语中的元音字母是a、e、i、o、u。
示例:
Input: GeeksForGeeks
Output: 5
Input: Hello Geeks
Output: 4
有两种方法可以计算字符串中的元音数量:
- 使用 for 循环
- 使用正则表达式
方法1:使用 for 循环
我们创建了一个名为“getvowels()”的用户定义函数,它读取一个字符串并将其与元音列表进行比较。它将字符串的每个字符与元音进行比较。当元音匹配时,它将增加元音计数的值。
示例: 下面的代码将演示这种方法。
function getVowels(string) {
let Vowels = 'aAeEiIoOuU';
let vowelsCount = 0;
for (let i = 0; i < string.length; i++) {
if (Vowels.indexOf(string[i]) !== -1) {
vowelsCount += 1;
}
}
return vowelsCount;
}
console.log("The Number of vowels in -" +
" A Computer Science Portal for Geeks:"
+ getVowels("A Computer Science Portal for Geeks"));
输出
The Number of vowels in - A Computer Science Portal for Geeks:12
方法2:使用正则表达式
正则表达式 是一系列字符,形成一个搜索模式。搜索模式可用于文本搜索和文本替换操作。
示例:
function vowelCount(str) {
const vowelRegex = /[aeiou]/gi;
const strMatches = str.match(vowelRegex);
if (strMatches) {
return strMatches.length;
} else {
return 0;
}
}
const string = "Geeksforgeeks";
const len = vowelCount(string);
console.log("Number of vowels:", len);
输出
Number of vowels: 5
极客教程