JS Coding Question #1: Count all vowels

JS Coding Question #1: Count all vowels

Sep 05, 2021

Interview Question #1:

Write a function that counts all vowels in a sentence❓🤔

If you need practice, try to solve this on your own. I have included 3 potential solutions below.

Note: There are many other potential solutions to this problem.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Code: https://codepen.io/angelo_jin/pen/zYzYdmQ

Solution #1: String match method

  • String.match method retrieves the result of matching a string against a regular expression.

function getVowelsCount(sentence) {
  return sentence.match(/[aeuio]/gi) ? sentence.match(/[aeuio]/gi).length : 0;
}

Solution #2: for-of And regex

  • simple iteration checking every characters in a sentence using regex does the job.

function getVowelsCount (sentence) {
    let vowelsCount = 0
    const vowels = ['a', 'e', 'i', 'o', 'u']

    for (let char of sentence) {
        if (/[aeiou]/gi.test(char.toLowerCase())) {
            vowelsCount++
        }
    }

    return vowelsCount
}

Solution #3: for-of AND array.includes

  • this is a good alternative instead of using solution above. Basically, replace regex test and utilize array includes instead.

function getVowelsCount (sentence) {
    let vowelsCount = 0
    const vowels = ['a', 'e', 'i', 'o', 'u']

    for (let char of sentence) {
        if (vowels.includes(char.toLowerCase())) {
            vowelsCount++
        }
    }

    return vowelsCount
}

Happy coding and good luck if you are interviewing!

Below is a video if you prefer this format:

https://youtu.be/SpxZ0hQP5cM

Enjoy this post?

Buy letscode77 a coffee

More from letscode77