I'm trying to write a javascript function that receives a string, and counts the amount of vowels. Displaying the count of each vowel, as well as a grand total. It works fine if every vowel is in the string, but if for example there aren't an A's or E's, it will return null.
Is there a way I can intercept this and replace null's with 0? Or is there a more efficient way to achieve this? Thank you to anyone who can help!
function countVowels(inString) {
return outString = (
"Total vowels: " + inString.match(/[aeiou]/gi).length +
"\nTotal A's: " + inString.match(/[a]/gi).length +
"\nTotal E's: " + inString.match(/[e]/gi).length +
"\nTotal I's: " + inString.match(/[i]/gi).length +
"\nTotal O's: " + inString.match(/[o]/gi).length +
"\nTotal U's: " + inString.match(/[u]/gi).length
);
}
<form>
Enter a string to count its vowels. <br>
<input type="text" id="inString"><br>
<button type="button" onclick="console.log(countVowels(inString.value))">Count vowels</button>
</form>
matchis kind of annoying that way. I’d try a different approach: writing afunction count(string, letter)that counts the number of instances ofletterinstring, and calling it withcount(inString, 'a'),count(inString, 'e'), etc.. You can save each of those and add them together to get the total number of vowels./[a]/gi, you can use/a/gi. This won't solve your issue, but it's a little cleaner...