So I am working on a project and as the title states, I am trying to find if the first letter of a string in javascript is a vowel. So far I have code that looks like this.
function startsWithVowel(word){
var vowels = ("aeiouAEIOU");
return word.startswith(vowels);
}
So I am working on a project and as the title states, I am trying to find if the first letter of a string in javascript is a vowel. So far I have code that looks like this.
function startsWithVowel(word){
var vowels = ("aeiouAEIOU");
return word.startswith(vowels);
}
Share
Improve this question
edited Dec 30, 2019 at 0:19
CertainPerformance
371k55 gold badges349 silver badges356 bronze badges
asked Dec 29, 2019 at 22:31
JamesJames
611 silver badge4 bronze badges
3
- @AndrewL64 different language but logic is still applicable. – A.J. Uppal Commented Dec 29, 2019 at 22:41
- @A.J.Uppal I have retracted the close vote. Thanks for the heads up. – AndrewL64 Commented Dec 29, 2019 at 23:05
- Does this answer your question? Check if a word begins with a vowel? – Vega Commented Nov 10, 2023 at 7:48
4 Answers
Reset to default 5You're quite close, just slice the word using [0]
and check that way:
function startsWithVowel(word){
var vowels = ("aeiouAEIOU");
return vowels.indexOf(word[0]) !== -1;
}
console.log("apple ".concat(startsWithVowel("apple") ? "starts with a vowel" : "does not start with a vowel"));
console.log("banana ".concat(startsWithVowel("banana") ? "starts with a vowel" : "does not start with a vowel"));
This works if you don't care about accent marks:
const is_vowel = chr => (/[aeiou]/i).test(chr);
is_vowel('e');
//=> true
is_vowel('x');
//=> false
But it will fail with accent marks monly found in French for example:
is_vowel('é'); //=> false
You can use String#normalize
to "split" a character: the base character followed by the accent mark.
'é'.length;
//=> 1
'é'.normalize('NFD').length;
//=> 2
'é'.normalize('NFD').split('');
//=> ["e", "́"] (the letter e followed by an accent)
Now you can get rid of the accent mark:
const is_vowel = chr => (/[aeiou]/i).test(chr.normalize('NFD').split('')[0]);
is_vowel('é');
//=> true
Credit to this fantastic answer to this question
startsWith
only accepts a single character. For this sort of functionality, use a regular expression instead. Take the first character from the word (word[0]
), and see whether its character is included in a case-insensitive character set, [aeiou]
:
function startsWithVowel(word){
return /[aeiou]/i.test(word[0]);
}
function startsWithVowel(word){
return /[aeiou]/i.test(word[0]);
}
console.log(
startsWithVowel('foo'),
startsWithVowel('oo'),
startsWithVowel('bar'),
startsWithVowel('BAR'),
startsWithVowel('AR')
);
ES6 oneliner:
const startsWithVowel = word => /[aeiou]/i.test(word[0]);