JavaScript(JS) JS count the number of vowels in a string
You can count the number of vowels in a string using JavaScript by looping through each character in the string and checking if it is a vowel. Here's an example:
erfer to:theitroad.comfunction countVowels(str) { const vowels = 'aeiouAEIOU'; let count = 0; for (let i = 0; i < str.length; i++) { if (vowels.includes(str[i])) { count++; } } return count; } const myString = 'Hello, World!'; const vowelCount = countVowels(myString); console.log(vowelCount);
In the above example, we define a function countVowels()
that takes a string str
as an argument. We declare a string vowels
that contains all the vowels in English. We initialize a variable count
to 0, which will be incremented for each vowel in the string. We then loop through each character in the string using a for
loop. For each character, we check if it is a vowel by using the includes()
method to see if the character is included in the vowels
string. If the character is a vowel, we increment the count
variable. Finally, we return the count
variable, which contains the total number of vowels in the string.
When the code is executed, the number of vowels in the string 'Hello, World!'
will be printed to the console, which is 3 in this case. Note that this implementation only counts ASCII vowels and does not handle accented or non-Latin vowels.