mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-12-19 06:58:15 +08:00
simplify the algo by using regex and String.prototype.match method, and modified the JS Doc
22 lines
539 B
JavaScript
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 };
|