How do I check for vowels in JavaScript?

前端 未结 10 795
忘了有多久
忘了有多久 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:21

    Personally, I would define it this way:

    function isVowel( chr ){ return 'aeiou'.indexOf( chr[0].toLowerCase() ) !== -1 }
    

    You could also use ['a','e','i','o','u'] and skip the length test, but then you are creating an array each time you call the function. (There are ways of mimicking this via closures, but those are a bit obscure to read)

    0 讨论(0)
  • 2020-12-01 03:21

    I kind of like this method which I think covers all the bases:

    const matches = str.match(/aeiou/gi];
    return matches ? matches.length : 0;
    
    0 讨论(0)
  • 2020-12-01 03:21

    I created a simplified version using Array.prototype.includes(). My technique is similar to @Kunle Babatunde.

    const isVowel = (char) => ["a", "e", "i", "o", "u"].includes(char);
    
    console.log(isVowel("o"), isVowel("s"));

    0 讨论(0)
  • 2020-12-01 03:22

    This is a rough RegExp function I would have come up with (it's untested)

    function isVowel(char) {
        return /^[aeiou]$/.test(char.toLowerCase());
    }
    

    Which means, if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true.

    0 讨论(0)
  • 2020-12-01 03:24

    benchmark

    I think you can safely say a for loop is faster.

    I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

    If you want to go for simplicity then just use

    function isVowel(c) {
        return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
    }
    
    0 讨论(0)
  • 2020-12-01 03:29

    cycles, arrays, regexp... for what? It can be much quicker :)

    function isVowel(char)
    {
        return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
    }
    
    0 讨论(0)
提交回复
热议问题