Hi I am trying to count the vowels of the input of the form in my HTML using javascript currently with no success.
Here is my HTML
<!doctype html>
<html>
<head>
<script src='p3-vowels.js'></script>
</head>
<body>
<form action="demo_form.asp">
Phrase: <input type="text" id = "input1" name="CountVowels" value="Put Phrase Here"><br>
<input type="button" id = "btn1" value="Check for Vowels">
</form>
</body>
</html>
and here is my javascript
function vow(form){
var a = form.CountVowels.value;
flag = 0;
for (var i = 0; i < a.length; i++){
switch (a[i]){
case 'a'
case 'e'
case 'i'
case 'o'
case 'u'
flag++;
break;
}
}
alert(flag);
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = vow;
}
window.onload = init;
Two problems:
1) You're missing colons after each case statement. I.e., it should be
case 'a': case 'b':
etc.not
2) You seem to be assuming that your click event will pass the form that the button is in to the function
vow
. It doesn't.Just change this:
To:
Also, you should really be programming with your Console window open to see JS errors. You would have seen both of those issues.
The
vow
function expects the form as a parameter, but you're not passing it. Give your form an ID so you can look it up and pass it.You were also missing the
:
character after eachcase
statement.In the interest of providing a more readable and concise solution, you can think of counting vowels as a reduction of characters to a single number.
We can do this by reducing the input string to a count of vowels as so:
Looking at the other answers, I think this is The Simplest Solution
One line of code and case insensitive. It splits the string at vowels and returns the array length. Why make it more complicated with loops and switch statements?
update: I really like freefaller's solution using match(), which is equal in simplicity. The solution here has a slight edge in that it has wider browser support. Would be interesting to know if there's any speed advantage between the methods.
Solution:
Run code snippet to test:
Replace your switch statement with
So
If you want to stick with the switch statement, you can, but you were missing colons ':'
The first method is simpler as you are basically checking if the letter exists in the vowel array.
Another option to the other answers is to use a regular expression. This is not necessarily easier to understand, or particularly efficient, but I'm giving it as an alternative. (It also continues to prove the proverb: give a 100 programmers a problem to solve and you'll get 100 solutions)
The following expression used in javascript will match all the vowels, and you can use the returning array to see how many there are...
The
i
makes it case insensitive, and theg
means global so it will pick up multiple times.Here is it in action...