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()
(A)
const countVowels = data => [...data.toLowerCase()].filter(char => 'aeiou'.includes(char)).length;
(B)
const countVowels = data => data.toLowerCase().split('').filter(char => 'aeiou'.includes(char)).length;
countVowels("Stackoverflow") // 4
Just use this function [for ES5] :
function countVowels(str){
return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;
}
Will work like a charm
The following works and is short:
function countVowels(str) {
return ( str = str.match(/[aeiou]/gi)) ? str.length : 0;
}
console.log(countVowels("abracadabra")); // 5
console.log(countVowels("")); // 0
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.
As the introduction of forEach in ES5 this could be achieved in a functional approach, in a more compact way, and also have the count for each vowel and store that count in an Object.
function vowelCount(str){
let splitString=str.split('');
let obj={};
let vowels="aeiou";
splitString.forEach((letter)=>{
if(vowels.indexOf(letter.toLowerCase())!==-1){
if(letter in obj){
obj[letter]++;
}else{
obj[letter]=1;
}
}
});
return obj;
}
Function vowels(str){
let count=0;
const checker=['a','e','i','o','u'];
for (let char of str.toLowerCase){
if (checker.includes(char)){
count++;
}
return count;
}
Function vowels(str){
const match = str.match(/[aeiou]/gi);
return match ? match.length : 0 ;
}