How to determine whether a String starts with a vowel or consonant

This is a short function for determining whether your string starts with a vowel or a consonant.

I recently had a usecase for this when working on some text generation and thought I would publish a simple function on here for free use, incase someone else would find it of use here. :smiley:

local function FirstIsVowel(str) 
	return str:match("^[AEIOUaeiou]") and true  -- cast to bool
end


Example use : 
if FirstIsVowel(Fruit) == true then
print("There is an" .. Fruit)  -- The first letter in the string is a vowel
else
 print ("There is a" .. Fruit) -- The first lettter in the string is a consonant
end

Here, Banana starts with a consonant and thus gets the output ā€œThere is a Bananaā€, Apple on the other starts with a vowel and gets the output ā€œThere is an Appleā€.

10 Likes

Whether or not you use an or a depends on the sound of the first character.
If it starts with a vowel sound you use an, if it starts with a consonant sound you use a.

This is why you would say ā€œa unicornā€ and not ā€œan unicornā€.

This is a cool use of pattern matching though :+1:

2 Likes

Well yes, I’m aware of this, the example usecase listed was just that, an example. The broader functionality listed works as it should, but you’re correct in what you’re saying.

1 Like