In this shot, we'll learn how to count the number of vowels present in a string using JavaScript.
Given a string s, count the number of vowels present in s and print it.
We will define a countVowels function to solve this.
The function countVowels takes a string as a parameter.
It returns 0 if no vowels are found in the given string. Otherwise, it returns the count of the vowels present in the given string.
s = "The quick brown fox jumps over the lazy dog"
The number of vowels in the string s are 11. Let us see how we can get this number in JavaScript.
//given stringvar s = "The quick brown fox jumps over the lazy dog"//function to count number of vowels in a stringfunction countVowels(s) {//regex to get vowelsvar c = s.match(/[aeiou]/gi);return c === null ? 0 : c.length;}//call countVowels functionconsole.log(countVowels(s))
s and assign a value to it.countVowels function, which accepts a string as a parameter and returns the count of the vowels present in that string./[aeiou]/gi as a parameter to the match method, which checks and returns characters which are matching the pattern,/[aeiou]/gi, that is it returns an array of characters that are vowels.null so we check for null and return 0 else return the length of the array.countVowels function and pass s as a parameter to it. We then print the returned value.