3

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);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
James
  • 41
  • 1
  • 4

4 Answers4

4

You'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"));
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
3

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 commonly 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

customcommander
  • 17,580
  • 5
  • 58
  • 84
2

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')
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

ES6 oneliner:

const startsWithVowel = word => /[aeiou]/i.test(word[0]);
  • Although your way to do it is pretty but if (just for a testing purpose ) provide index more then the length of string. it's says true for them. vowels.indexOf(word[0])) is perfect for this purpose. – Bangash Oct 29 '20 at 12:44
  • Can you give more details about this one-liner function? In my case this is not working:`set enum(text) { let startsWithVowel = (text) => /[aeiou]/i.indexOf(text[0]); this.title = startsWithVowel ? "Créer un nouvel ${text.slice(0, -1)}" : "Créer un nouveau ${text.slice(0, -1)}" }` – Yohan W. Dunon Jul 21 '21 at 13:27