Last Updated: August 03, 2016
·
1.846K
· shinjukudev

Vowel Count (JS Algorithm)

Basic algorithm that takes in a string and returns the count of vowels that appear in the string. Uses a nested for loop, which isn't optimal for larger strings. I wonder if anybody has a better solution?

function vowel_count(str) {
  'use strict';

  if(typeof str != 'string') {
    return false;
  }

  var count = 0;
  var pattern = /[aeiou]/i;

  for(var i = 0; i < str.length; i++) {
    if(str[i].match(pattern)) {
      count++;
    }
  }

  return count;
}

var sentence = 'This should have 9 vowels in it';

var output = vowel_count(sentence);

console.log(output);

3 Responses
Add your response

you don't need to regexp.match each character. regexp.match returns all the matches in the array, and you can get the length of the array once without a for loop.

function vowel_count(str)
{
  'use strict';

  if(typeof str != 'string') {
    return false;
  }

  var count = 0;
  var pattern = /[aeiou]/ig;
  var matches = str.match(pattern);
  return matches != null? matches.length:0;
}
over 1 year ago ·

@jeffcheung Hey! Thanks for the feedback! That's a really good point

over 1 year ago ·

@jeffcheung In that case, we can get rid of var count = 0 as well :)

over 1 year ago ·