function endsWithVowel(str) {
if (!str || str.length === 0) {
return false; // Or handle empty strings as needed
}
const vowels = "aeiouAEIOU";
const lastChar = str.charAt(str.length - 1);
return vowels.includes(lastChar);
}
// Examples
console.log(endsWithVowel("hello")); // true
console.log(endsWithVowel("world")); // false
console.log(endsWithVowel("APPLE")); // true
console.log(endsWithVowel("")); // false (or handle as needed)
console.log(endsWithVowel(null)); // false (or handle as needed)
console.log(endsWithVowel(undefined)); // false (or handle as needed)
// More robust handling of null/undefined/empty strings:
function endsWithVowelRobust(str) {
if (typeof str !== 'string' || !str) { // Check for non-string or empty/null/undefined
return false;
}
const vowels = "aeiouAEIOU";
const lastChar = str.charAt(str.length - 1);
return vowels.includes(lastChar);
}
Explanation and Improvements:
-
Handle Empty/Null/Undefined: The original version could throw errors if
str
was null, undefined, or an empty string. TheendsWithVowelRobust
function explicitly checks for these cases and returnsfalse
. You can adjust the return value to suit your specific needs. -
Clearer Variable Names: Using
vowels
instead of justv
makes the code more readable. -
Case-Insensitive: The
vowels
string includes both uppercase and lowercase vowels, making the function case-insensitive. -
includes()
Method: Usingvowels.includes(lastChar)
is a concise and efficient way to check if the last character is a vowel. -
Comments and Examples: Adding comments and examples makes the code easier to understand and test.
Alternative using Regular Expression:
function endsWithVowelRegex(str) {
if (typeof str !== 'string' || !str) {
return false;
}
return /[aeiouAEIOU]$/.test(str);
}
// Examples (same results as above)
console.log(endsWithVowelRegex("hello")); // true
console.log(endsWithVowelRegex("world")); // false
console.log(endsWithVowelRegex("APPLE")); // true
console.log(endsWithVowelRegex("")); // false
console.log(endsWithVowelRegex(null)); // false
console.log(endsWithVowelRegex(undefined)); // false
The regular expression /[aeiouAEIOU]$/
checks if the string ends ($
) with any of the characters within the square brackets (the vowels). This is a very compact way to achieve the same result.
Choose the method that you find most readable and maintainable for your project. The includes()
version is often slightly faster for simple vowel checks, while the regular expression approach can be more flexible if you need to handle more complex patterns in the future.