Exercise 22: Counting Vowels in a String with JavaScript
Discover how to count vowels in a string using JavaScript. This exercise is ideal for practicing iterations and regular expressions. The main purpose is to practice using them.forand conditionals to analyze the content of a string, counting the vowels.
Activity
-
Ask the user to enter a word or phrase.
-
Use a loop
forto iterate through each character of the entered string. -
Check if the current character is a vowel (
a,e,i,o,u(in lowercase or uppercase). -
If it is a vowel, increment a counter.
-
At the end of the loop, display the total number of vowels found in the console.
Solution
Step 1: Create the index.html file
HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Contar vocales en una cadena</title>
</head>
<body>
<h1>Ejercicio 22: Contar vocales en una cadena</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
JavaScript
let texto = prompt("Ingresa una palabra o frase:");
let contadorVocales = 0;
for (let i = 0; i < texto.length; i++) {
let caracter = texto[i].toLowerCase();
if (
caracter === "a" ||
caracter === "e" ||
caracter === "i" ||
caracter === "o" ||
caracter === "u"
) {
contadorVocales++;
}
}
console.log(`La cantidad de vocales en "${texto}" es: ${contadorVocales}`);
info
🔎Check the sectionControl instructions in JavaScriptwhere you will find more information on this topic.