w3resource

CoffeeScript function: Counts the number of vowels within a string

CoffeeScript Function : Exercise-14 with Solution

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

Note : As the letter 'y' can be regarded as both a vowel and a consonant, we do not count 'y' as a vowel here.
Example string : 'The quick brown fox'
Expected Output : 5

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="//jashkenas.github.io/coffee-script/extras/coffee-script.js"></script>
  <title>Counts the number of vowels within a string
  </title>
</head>
<body>

</body>
</html>

CoffeeScript Code:

vowel_count = (str1) ->
  vowel_list = 'aeiouAEIOU'
  vcount = 0
  x = 0
  while x < str1.length
    if vowel_list.indexOf(str1[x]) != -1
      vcount += 1
    x++
  vcount

console.log vowel_count('The quick brown fox')

Sample Output:

5

Live Demo:

See the Pen coffeescript-exercise-14 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.