Files
JavaScript/String/CountVowels.js
Fahim Faisaal 68ca0ceeef merge: optimize the countVowels algo (#886)
* pref: optimize the count vowels algo

simplify the algo by using regex and String.prototype.match method, and modified the JS Doc

* fix: resolve all requests

* pref: optimize the algo by regex

ignore the useless traverse in best case by the help of regex and String.prototype.replace method

* test: add four new test cases

* Revert "test: add four new test cases"
This reverts commit 4609833da146beafe839682d7558edf9f64c96fc.

* style: fromat with standard js
2022-02-17 17:30:04 +05:30

22 lines
534 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 vowels
* @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 }