I\'m using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes()
Short and ES6, you can use the function count(str);
const count = str => (str.match(/[aeiou]/gi) || []).length;
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.
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('ffffd')); // 0
This is the shortest solution
function getCount(str) {
return (str.match(/[aeiou]/ig)||[]).length;
}
You can use the simple includes function, which returns true if the given array contains the given character, and false if not.
Note: The includes() method is case sensitive. So before comparing a character convert it to lowercase to avoid missing all the possible cases.
for (var i = 0; i <= string.length - 1; i++) {
if ('aeiou'.includes(string[i].toLowerCase())) {
vowelsCount += 1;
}
}
Use match
but be careful as it can return a null if no match is found
const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length);