Counting number of vowels in a string with JavaScript
You can actually do this with a small regex:
function getVowels(str) {
var m = str.match(/[aeiou]/gi);
return m === null ? 0 : m.length;
}
This just matches against the regex (g
makes it search the whole string, i
makes it case-insensitive) and returns the number of matches. We check for null
incase there are no matches (ie no vowels), and return 0 in that case.
Convert the string to an array using the Array.from()
method, then use the Array.prototype.filter()
method to filter the array to contain only vowels, and then the length
property will contain the number of vowels.
const countVowels = str => Array.from(str)
.filter(letter => 'aeiou'.includes(letter)).length;
console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
console.log(countVowels('test')); // 1
console.log(countVowels('ddd')); // 0
function countVowels(subject) {
return subject.match(/[aeiou]/gi).length;
}
You don't need to convert anything, Javascript's error handling is enough to hint you on such a simple function if it will be needed.
Short and ES6, you can use the function count(str);
const count = str => (str.match(/[aeiou]/gi) || []).length;