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);
Written by shinjukudev
Related protips
3 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#