How do I check for vowels in JavaScript?

前端 未结 10 796
忘了有多久
忘了有多久 2020-12-01 02:55

I\'m supposed to write a function that takes a character (i.e. a string of length 1) and returns true if it is a vowel, false otherwise. I came up with two functions, but do

相关标签:
10条回答
  • 2020-12-01 03:33

    Lots of answers available, speed is irrelevant for such small functions unless you are calling them a few hundred thousand times in a short period of time. For me, a regular expression is best, but keep it in a closure so you don't build it every time:

    Simple version:

    function vowelTest(s) {
      return (/^[aeiou]$/i).test(s);
    }
    

    More efficient version:

    var vowelTest = (function() {
      var re = /^[aeiou]$/i;
      return function(s) {
        return re.test(s);
      }
    })();
    

    Returns true if s is a single vowel (upper or lower case) and false for everything else.

    0 讨论(0)
  • 2020-12-01 03:35
      //function to find vowel
    const vowel = (str)=>{
      //these are vowels we want to check for
      const check = ['a','e','i','o','u'];
      //keep track of vowels
      var count = 0;
      for(let char of str.toLowerCase())
      {
        //check if each character in string is in vowel array
        if(check.includes(char)) count++;
      }
      return count;
    }
    
    console.log(vowel("hello there"));
    
    0 讨论(0)
  • 2020-12-01 03:41
    function isVowel(char)
    {
      if (char.length == 1)
      {
        var vowels = "aeiou";
        var isVowel = vowels.indexOf(char) >= 0 ? true : false;
    
        return isVowel;
      }
    }
    

    Basically it checks for the index of the character in the string of vowels. If it is a consonant, and not in the string, indexOf will return -1.

    0 讨论(0)
  • 2020-12-01 03:43
    function findVowels(str) {
      return str.match(/[aeiou]/ig);
    }
    
    findVowels('abracadabra'); // 'aaaaa'
    

    Basically it returns all the vowels in a given string.

    0 讨论(0)
提交回复
热议问题