JavaScript 程序:计算字符串中的元音字母数量

要理解此示例,您应了解以下 JavaScript 编程 主题


字母 a、e、i、ou 称为元音字母。除这 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

另请阅读

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算给定单词中每个字母的出现次数。

  • 返回一个对象,其中键是字母,值是它们的计数。
  • 假设给定的字符串是 "banana"。字母 'b' 出现一次,'a' 出现三次,'n' 出现两次。
  • 因此,我们预期的输出将是 {b: 1, a: 3, n: 2}
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战