How can I get the number of uppercase and lowercase vowels in a variable in JavaScript.
var person = new Object();
person = prompt("Introduce tus datos");
//Numero de vocales
var numVocales;
for (i = 0; i < 10; i++) {
var vocal;
if (i = 0){
vocal = "a";
}
else if (i = 1){
vocal = "e";
}
else if (i = 2){
vocal = "i";
}
else if (i = 3){
vocal = "o";
}
else if (i = 4){
vocal = "u";
}
else if (i = 5){
vocal = "A";
}
else if (i = 6){
vocal = "E";
}
else if (i = 7){
vocal = "I";
}
else if (i = 8){
vocal = "O";
}
else if (i = 9){
vocal = "U";
}
var aux = person.indexOf(vocal);
if(aux != -1){
numVocales++;
}
}
alert(numVocales);
I can't display the information in the alert, it may be that the for is wrong. Also, I don't know if using indexOf() will get me the first matching letter. I mean, if I have ana, would using indexOf() return one or two?
The code has quite a few bugs, so I'll try to list them and leave it to you to fix it:
This first line is of no use to you, you can delete it, because in the next line you assign a new value to
person
This loop doesn't make much sense: up to 10 because you have 10 possible letters to search for? What you have to do is loop through the string in
person
.This is an error that often goes unnoticed by newbies: instead of using
==
(compare if they are equal) you have used an assignment. What it does is that i is equal to 0 and that is the value to check. Since 0 is "false", go to the next if...Here we have the same error again, you assign 1 to i, with the difference that 1 is "true" and the comparisons are over. This means that in each iteration i is equal to 1 and the loop never ends, hanging the execution. That's why you never get to the
alert
.Clue to find vowels:
Pablo Lozano's solution will serve you better because it is a more complete analysis of your code. I am going to give you a solution that is much shorter than what you are trying to do.
The idea is to use regular expressions to find the occurrences of vowels (
[aeiou]
) within the string. It finds them all by the modifierg
and is not case sensitive by the modifieri
.Here an example: