Counting number of vowels in a string with JavaScript

前端 未结 18 1636
旧巷少年郎
旧巷少年郎 2020-12-08 23:53

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()

18条回答
  •  生来不讨喜
    2020-12-09 00:34

    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;
      }
    }
    

提交回复
热议问题