Let’s write a simple JavaScript to count the number of vowels present in a string and print it.
And also you will learn the below ideas from this JavaScript tutorial, such as:
1. How to define an array in JavaScript
2. How to find the length of a String in JavaScript
3. How to create a function and call it in JavaScript
4. How to loop through string characters in JavaScript
Before writing the entire code, here is the JavaScript function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function findVowels(){[ //set an array of vowels here var vowels = ['a', 'e', 'i', 'o', 'u']; var vowelsFound = []; //get the string from textbox var txt = document.getElementById("txt").value; //loop each character from string and find the vowels for(i=0; i < txt.length; i++){ if(vowels.indexOf(txt[i]) != -1){ vowelsFound.push(txt[i]); } } document.getElementById("result").innerHTML = "<p><strong>Vowels found:</strong> "+ vowelsFound +"</p><p><strong>Vowels count:</strong> "+ vowelsFound.length +"</p>"; } |
Now, let’s write the entire JavaScript example snippet to count the number of vowels in a String:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>JavaScript to find Vowels from String!</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Load Bootstrap library for better UI look & feel --> <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> <!-- Load the jQuery & jQuery UI libraries --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script> function findVowels(){[ //set an array of vowels here var vowels = ['a', 'e', 'i', 'o', 'u']; var vowelsFound = []; //get the string from textbox var txt = document.getElementById("txt").value; //loop each character from string and find the vowels for(i=0; i < txt.length; i++){ if(vowels.indexOf(txt[i]) != -1){ vowelsFound.push(txt[i]); } } document.getElementById("result").innerHTML = "<p><strong>Vowels found:</strong> "+ vowelsFound +"</p><p><strong>Vowels count:</strong> "+ vowelsFound.length +"</p>"; } </script> </head> <body> <div class="container"> <br /> <h2>JavaScript to find Vowels in a String by tutorialsmade.com</h2> <br /> <form action="" id="myform"> <div class="form-group"> <label for="txt">Enter Text:</label> <input type="text" class="form-control req" id="txt" > </div> <div class="form-group"> <div id="result"></div> </div> <button type="button" class="btn btn-success" onclick="findVowels()">Submit</button> </form> </div> </body> </html> |
I have used bootstrap to make the page look neat, you can skip it if you don’t want.
You can see the demo of above JavaScript here: