Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of vowels in a string with JavaScript

I'm using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes() help at all considering it is a string? I would like to use something like string.includes("a", "e", "i", "o", "u") if at all possible to clean up the conditional statement. Also, is it needed to convert the input into a string?

function getVowels(str) {
  var vowelsCount = 0;

  //turn the input into a string
  var string = str.toString();

  //loop through the string
  for (var i = 0; i <= string.length - 1; i++) {

  //if a vowel, add to vowel count
    if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") {
      vowelsCount += 1;
    }
  }
  return vowelsCount;
}
like image 432
dcook Avatar asked Apr 04 '15 19:04

dcook


Video Answer


1 Answers

You can use the simple includes function, which returns true if the given array contains the given character, and false if not.

Note: The includes() method is case sensitive. So before comparing a character convert it to lowercase to avoid missing all the possible cases.

for (var i = 0; i <= string.length - 1; i++) {
  if ('aeiou'.includes(string[i].toLowerCase())) {
    vowelsCount += 1;
  }
}
like image 147
Vivek Potula Avatar answered Sep 21 '22 03:09

Vivek Potula