JS Algorithm – Number of vowels

Western Wall, Jerusalem, Israel

Write a function that returns the number of vowels used in a string. Vowels are the characters ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’.

Examples
vowels(‘Hi There!’) –> 3
vowels(‘Why do you ask?’) –> 4
vowels(‘Why?’) –> 0

First solution:

function vowels(str) {
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  let counter = 0;

  str.split('').forEach((letter) => {

    if (vowels.includes(letter.toLowerCase())) {
      counter += 1;
    }
  });

  return counter;
}

vowels('Why do you ask?');

Result:

Second solution:

function vowels(str) {
  let counter = 0;
  const checker = "aeiou";

  // Go through every character of my string
  // and convert the main string to lower case
  for (let char of str.toLowerCase()) {

    // Check if in our checker string include the
    // current char of the main string
    if (checker.includes(char)) {
      // if is that character is included
      // in our checker then increment the counter
      counter ++;
    }
  }

  return counter;
}

vowels('Why do you ask?');

Result:

Third solution:

function vowels(str) {
  // With regular expressions
  // and will return an array With
  // the matches that found
  const matches = str.match(/[aeiou]/gi);

  // Return the number of vowels
  return matches ? matches.length : 0
}

vowels('Why do you ask?');

Result:

Four solution:

function vowels(str) {
  const text = str.split('');
  let counter = 0;

  text.filter((letter) => {
    if (letter.toLowerCase() === 'a'
        || letter.toLowerCase() === 'e'
        || letter.toLowerCase() === 'i'
        || letter.toLowerCase() === 'o'
        || letter.toLowerCase() === 'u') {
          counter += 1;
    }
  })

  return counter;
}

vowels('Why do you ask?');

Result:

By Cristina Rojas.