DEV Community

Cover image for JS Coding Question #1: Count all vowels [3 Solutions]
Let's Code
Let's Code

Posted on • Updated on

JS Coding Question #1: Count all vowels [3 Solutions]

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;
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Happy coding and good luck if you are interviewing!

If you want to support me - Buy Me A Coffee

In case you like a video instead of bunch of code πŸ‘πŸ˜Š

Discussion (11)

Some comments have been hidden by the post's author - find out more