Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 计算字符串中元音个数的程序

用于计算字符串中元音数量的 JavaScript 程序

在这个例子中,您将学习编写一个 JavaScript 程序来计算字符串中元音的数量。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 字符串 Javascript 字符串匹配() Javascript 字符串包含()
五个字母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。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4