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
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.
//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"));
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.
function findVowels(str) {
return str.match(/[aeiou]/ig);
}
findVowels('abracadabra'); // 'aaaaa'
Basically it returns all the vowels in a given string.