给定特定的字符串,写个方法判断是否以元字母结尾

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:

  1. Handle Empty/Null/Undefined: The original version could throw errors if str was null, undefined, or an empty string. The endsWithVowelRobust function explicitly checks for these cases and returns false. You can adjust the return value to suit your specific needs.

  2. Clearer Variable Names: Using vowels instead of just v makes the code more readable.

  3. Case-Insensitive: The vowels string includes both uppercase and lowercase vowels, making the function case-insensitive.

  4. includes() Method: Using vowels.includes(lastChar) is a concise and efficient way to check if the last character is a vowel.

  5. 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.

posted @ 2024-12-10 09:07  王铁柱6  阅读(22)  评论(0)    收藏  举报