Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);   } } 
like image 916
Max Avatar asked Mar 30 '11 14:03

Max


People also ask

How do you check if a character is a vowel in JavaScript?

The function checks if it's vowel. Then the input is checked to see if it's length is 1. If it's 1, call the function. If it's greater than 1, ask for another input until the length is 1.

Is there a vowel in there JavaScript?

JavaScript contains 3 vowels.

How do you find a vowel in a string?

To find the vowels in a given string, you need to compare every character in the given string with the vowel letters, which can be done through the charAt() and length() methods. charAt() : The charAt() function in Java is used to read characters at a particular index number.


1 Answers

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 } 
like image 73
Raynos Avatar answered Sep 26 '22 10:09

Raynos