loading...

Find The Vowels used in a String with JavaScript

tadea profile image Tadea Simunovic ・1 min read

Count the vowels in a string with JavaScript. Short and simple!

Challenge

---Directions
Write a function that returns the number of vowels used in a string. To confirm, vowels are the characters 'a', 'e', 'i', 'o' and 'u'.
---Example
vowels('Hello') ---> 2
vowels('Javascript') ---> 3
vowels('crypt') ---> 0

We will start with creating a counter variable starting with 0, and then we will iterate through our string and make sure we will lowerCase our vowels.

function vowels(str) {
  let counter = 0;

   for (let char of str.toLowerCase()){

   }
 }

We could of do a bunch of IF statements, but our code would look messy. Instead, we will use the helper method includes() that determines whether an array includes a certain value among its entries, returning true or false as appropriate. Read more about it here.

Let's create an array that will hold all of our vowels.

const check = ['a','e','i','o','u']

Now we have to use some logic in our loop. If the char that we are looking for is included in an array we will increment the counter. We'll iterate through all of our characters and then return them.

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

   for (let char of str.toLowerCase()){
    if (check.includes(char)) {
      counter++
     }
   }
   return counter
 }

Output in console.

// vowels("Today is a rainy day!") --> 7

// vowels("Shy gypsy slyly spryly tryst by my crypt") --> 0

Posted on Jul 3 by:

tadea profile

Tadea Simunovic

@tadea

From teacher πŸ‘©πŸ»β€πŸ« to software engineer πŸ‘©πŸ»β€πŸ’» Full stack Web Developer with passion for software engineering. #rubyOnRails #javaScript #react #html #css

Discussion

markdown guide
 

I know this is massively illegible compared to your beautifully constructed routine (which might well be how I'd write it because I'm all for legibility) but the short version might be coded as:

const count = str.split('').reduce((a,c)=>a + ("aeiouAEIOU".includes(c) ? 1 : 0), 0)
 

Nice post! Also very important for beginners since you structured and explained very well. Good Job. If i had to do it, i would go with regex:

str.replace(/[^aeiou]/ig,'').length;

It just removes everything that is not a vowel and returns the new string size. The i tells it to be case insensitive.

 

Great advice! Thank you