Counting number of vowels in a string with JavaScript

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

    This could also be solved using .replace() method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:

    function vowelCount(str) {
      return str.replace(/[^aeiou]/gi, "").length;
    };
    

    or if you prefer ES6

    const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )
    

提交回复
热议问题