return count outside the for loop or use RegExp /[^aeiou]/ig as the first parameter .replace() with "" as a replacement string, get .legnth string returned by .replace()
vowelLength = "aide".replace(/[^aeiou]/ig, "").length; console.log(vowelLength); vowelLength = "gggg".replace(/[^aeiou]/ig, "").length; console.log(vowelLength);
RegExp Description
Character set
[^xyz] Negative or padding character set. That is, it matches any that is not enclosed in parentheses.
Flags
i ignore case
g global compliance; find all matches, not stop after the first match
Using the extended element Array.prototype.reduce() , String.prototype.indexOf() or String.prototype.contains() , where supported
const v = "aeiouAEIOU"; var vowelLength = [..."aide"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0); console.log(vowelLength); var vowelLength = [..."gggg"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0); console.log(vowelLength);
Alternatively, instead of creating a new string or a new array to get the .length property or repeating the characters of the string, you can use the for..of , RegExp.prototype.test with RegExp /[aeiou]/i to increase the initial variable by 0 if .test() evaluates to true for the character passed.
var [re, vowelLength] = [/[aeiou]/i, 0]; for (let c of "aide") re.test(c) && ++vowelLength; console.log(vowelLength); vowelLength = 0; for (let c of "gggg") re.test(c) && ++vowelLength; console.log(vowelLength);
source share