Palindrome String Checker
Determining if a string is a palindrome is a classic programming exercise. A palindrome is a string that reads the same forwards and backward, ignoring case and non-alphanumeric characters. This challenge will test your ability to manipulate strings and implement a robust palindrome check in JavaScript.
Problem Description
You are tasked with creating a JavaScript function called isPalindrome that takes a single string as input and returns true if the string is a palindrome, and false otherwise. The function should ignore case and non-alphanumeric characters (letters and numbers only) when determining if the string is a palindrome. This means spaces, punctuation, and other special characters should be removed before the check.
Key Requirements:
- The function must accept a string as input.
- The function must return a boolean value (
trueorfalse). - Case should be ignored (e.g., "Racecar" should be considered a palindrome).
- Non-alphanumeric characters should be ignored (e.g., "A man, a plan, a canal: Panama" should be considered a palindrome).
- The function should handle empty strings and strings with a single character correctly.
Expected Behavior:
The function should accurately identify palindromes and non-palindromes based on the criteria outlined above.
Examples
Example 1:
Input: "Racecar"
Output: true
Explanation: The string "Racecar" reads the same forwards and backward, ignoring case.
Example 2:
Input: "A man, a plan, a canal: Panama"
Output: true
Explanation: After removing non-alphanumeric characters and converting to lowercase, the string becomes "amanaplanacanalpanama", which is a palindrome.
Example 3:
Input: "hello"
Output: false
Explanation: The string "hello" does not read the same forwards and backward.
Example 4:
Input: ""
Output: true
Explanation: An empty string is considered a palindrome.
Example 5:
Input: "a"
Output: true
Explanation: A single-character string is considered a palindrome.
Constraints
- The input string can contain any ASCII characters.
- The input string's length can be up to 1000 characters.
- The function should execute in a reasonable time (e.g., less than 100ms for strings of length 1000).
Notes
- Consider using regular expressions to efficiently remove non-alphanumeric characters.
- Think about how to handle case-insensitive comparisons.
- A two-pointer approach (one starting from the beginning and one from the end of the string) can be an efficient way to check for palindromes.
- Remember to handle edge cases like empty strings and single-character strings.