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); } }
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.
JavaScript contains 3 vowels.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With