Max
Max

Reputation: 1213

How do I check for vowels in JavaScript?

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 don't know which one is better performing and which way I should prefer. The one with RegEx is way simpler but I am unsure whether I should try to avoid using RegEx or not?

Without RegEx:

function isVowel(char) {
  if (char.length == 1) {
    var vowels = new Array("a", "e", "i", "o", "u");
    var isVowel = false;

    for (e in vowels) {
      if (vowels[e] == char) {
        isVowel = true;
      }
    }

    return isVowel;
  }
}

With RegEx:

function isVowelRegEx(char) {
  if (char.length == 1) {
    return /[aeiou]/.test(char);
  }
}

Upvotes: 39

Views: 170453

Answers (12)

Intellidroid
Intellidroid

Reputation: 1055

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

const matches = str.match(/[aeiou]/gi);
return matches ? matches.length : 0;

Upvotes: 4

Madhusanka Edirimanna
Madhusanka Edirimanna

Reputation: 1428

Basically it returns all the vowels in a given string.

function vowels(s) {
  let vowels = ["a", "e", "i", "o", "u"];

  for(let v of s) {
    if(vowels.includes(v))
        console.log(v);
  }
}

Upvotes: 2

Yuniac
Yuniac

Reputation: 583

This is the way I did it, on the first occurrence of a vowel in any given word it breaks out of the loop and returns true.

const vowels = ["a", "e", "i", "o", "u", "y"];

function isVowel(word) {
    let result = false;
    for (let i = 0; i < word.length; i++) {
        if (vowels.includes(word[i])) {
            result = true;
            break;
        }
    }
    return result;

Upvotes: 1

Penny Liu
Penny Liu

Reputation: 17498

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"));

Upvotes: 0

RobG
RobG

Reputation: 147553

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.

Upvotes: 34

Jos&#233; Salgado
Jos&#233; Salgado

Reputation: 1072

function findVowels(str) {
  return str.match(/[aeiou]/ig);
}

findVowels('abracadabra'); // 'aaaaa'

Basically it returns all the vowels in a given string.

Upvotes: 6

Kunle Babatunde
Kunle Babatunde

Reputation: 19

  //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"));

Upvotes: -1

Raynos
Raynos

Reputation: 169551

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
}

Upvotes: 55

cwallenpoole
cwallenpoole

Reputation: 82088

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)

Upvotes: 4

Emmerman
Emmerman

Reputation: 2343

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

Upvotes: 9

Buhake Sindi
Buhake Sindi

Reputation: 89209

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.

Upvotes: 4

H&#229;vard
H&#229;vard

Reputation: 10080

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.

Upvotes: 2

Related Questions