Tuesday, July 20, 2021

Junior Developer Central JS Practice Exercise - 22

 
Question: 

Write a Javascript function that accepts a string as a parameter and counts the number of vowels within the string. 




Answer: 

function vowelCount (str) {

  let vowels = /[aeiou]/gi;
  let result = str.match(vowels);
  let count = result.length;
  return count; 
  
  };




> we declare a function 'vowelCount' 
> it has one parameter 'str', which is a string
> we declare a variable 'vowels' and initialize it with the 5 vowels
> the 'g' modifier is used on the 'vowels' variable to perform a global match 
> a global match will find all matches and will not stop after finding the first match
additionally  the 'i' modifier is used on the 'vowels' variable to perform case insensitive matching
> we declare another variable 'result' and initialize it with the result we get when we use the match () method on the 'str' parameter
> the match() method searches a string for a match against a regular expression and returns the matches as an array object
> we want to match the 'str' with the elements in the 'vowels' variable and store the results in the 'result' array
> we declare another variable 'count' and initialize it with a value we get by using the length property on the array 'result' which will give us the total number of elements in the 'result' array
> we return the 'count' variable

No comments:

Post a Comment