Files
JavaScript/String/CountVowels.js
Fahim Faisaal a2822e17b6 pref: optimize the count vowels algo
simplify the algo by using regex and String.prototype.match method, and modified the JS Doc
2022-02-16 19:47:01 +06:00

22 lines
539 B
JavaScript

/**
* @function countVowels
* @description Given a string of words or phrases, count the number of vowels.
* @param {String} str - The input string
* @return {Number} - The number of vowel
* @example countVowels("ABCDE") => 2
* @example countVowels("Hello") => 2
*/
const countVowels = (str) => {
if (typeof str !== 'string') {
throw new TypeError('Input should be a string');
}
const vowelRegex = /[aeiou]/gi;
const vowelsArray = str.match(vowelRegex) || [];
return vowelsArray.length;
}
export { countVowels };