Counting number of vowels in a string with JavaScript

前端 未结 18 1643
旧巷少年郎
旧巷少年郎 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:21

    You can actually do this with a small regex:

    function getVowels(str) {
      var m = str.match(/[aeiou]/gi);
      return m === null ? 0 : m.length;
    }
    

    This just matches against the regex (g makes it search the whole string, i makes it case-insensitive) and returns the number of matches. We check for null incase there are no matches (ie no vowels), and return 0 in that case.

提交回复
热议问题