JavaScript Program to Check Whether a String is Palindrome or Not
Learn JavaScript Program to Check Whether a String is Palindrome or Not step by step with clear examples and exercises.
Why This Matters
In this comprehensive lesson, we will delve into creating a JavaScript program that checks whether a given string is palindrome or not. Mastering this skill is crucial as it plays an essential role in various programming tasks and interviews, allowing you to identify symmetrical strings that read the same forward and backward. Palindromes are important in natural language processing, computer science, and mathematics, making them a valuable tool for developers to understand and use.
Prerequisites
Before proceeding with the core concept, ensure you have a solid understanding of the following JavaScript fundamentals:
- Basic JavaScript syntax
- Variables and data types
- Control structures (if...else statements)
- Loops (for loops)
- Regular expressions (optional but recommended for handling special characters)
- Understanding of functions and function parameters
Core Concept
A string is considered palindrome if it remains unchanged when its characters are reversed. For example, "racecar" and "madam" are palindromes because they read the same way forward and backward. On the other hand, "hello" is not a palindrome since its reverse is "olleh".
To check if a string is palindrome in JavaScript, we can compare each character with its corresponding reversed counterpart. If all characters match, then the given string is a palindrome. However, there are additional considerations to keep in mind:
- Case sensitivity: By default, JavaScript is case-sensitive when comparing strings. To handle both lowercase and uppercase letters, we can convert the input string to either lowercase or uppercase before comparison.
- Special characters and spaces: When checking for palindromes, it's important to consider only the alphanumeric characters (letters and numbers) and ignore spaces, punctuation marks, and other symbols. To achieve this, we can use regular expressions to remove non-alphanumeric characters from the input string before comparison.
- Handling odd-length palindromes: If a palindrome has an odd length, its middle character should be compared with itself during the comparison process.
- Empty strings: An empty string is technically considered a palindrome because it remains unchanged when reversed. Make sure your function handles this case properly.
- Performance optimization: To optimize the performance of your palindrome checking function, consider stopping the comparison as soon as a mismatch is found, instead of comparing the entire string. Another approach is to use regular expressions for character matching and removal of non-alphanumeric characters.
Worked Example
Let's create a simple function called isPalindrome() that checks whether a given string is palindrome or not:
function isPalindrome(str) {
// Find the length of the input string
const len = str.length;
// Initialize two pointers, start and end, at opposite ends of the string
let start = 0;
let end = len - 1;
// Loop through the string until the pointers meet or cross each other
while (start < end) {
// If characters at the starting and ending positions don't match, return false
if (!isMatch(str[start], str[end])) {
return false;
}
// Move the pointers towards each other
start++;
end--;
}
// If all characters match, return true
return true;
}
// Helper function to handle case sensitivity and special characters
function isMatch(char1, char2) {
const regex = /[A-Za-z0-9]/;
// Convert both characters to lowercase and remove any non-alphanumeric characters
const cleanedChar1 = regex.test(char1.toLowerCase()) ? char1.toLowerCase().replace(/[^A-Za-z0-9]/g, '') : '';
const cleanedChar2 = regex.test(char2.toLowerCase()) ? char2.toLowerCase().replace(/[^A-Za-z0-9]/g, '') : '';
return cleanedChar1 === cleanedChar2;
}
Now we can test our function with some examples:
console.log(isPalindrome("racecar")); // Output: true
console.log(isPalindrome("hello")); // Output: false
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("A man, a plan, a canal: Panama")); // Output: true (ignoring spaces and punctuation)
Common Mistakes
- Ignoring spaces and special characters: When checking for palindromes, it's important to consider only the alphanumeric characters (letters and numbers) and ignore spaces, punctuation marks, and other symbols.
- Not handling odd-length palindromes: If a palindrome has an odd length, its middle character should be compared with itself during the comparison process.
- Forgetting to handle empty strings: An empty string is technically considered a palindrome because it remains unchanged when reversed. Make sure your function handles this case properly.
- Case sensitivity: By default, JavaScript is case-sensitive when comparing strings. If you want to ignore case sensitivity, make sure to convert both characters to the same case before comparison.
- Performance optimization: To optimize the performance of your palindrome checking function, consider stopping the comparison as soon as a mismatch is found, instead of comparing the entire string. Another approach is to use regular expressions for character matching and removal of non-alphanumeric characters.
- Incorrect handling of special characters: When using regular expressions to remove non-alphanumeric characters, make sure that you are correctly capturing all special characters, including spaces, punctuation marks, and symbols.
- Not accounting for unicode characters: If your program needs to handle palindromes with unicode characters, ensure that your function can properly convert these characters to their ASCII equivalents before comparison.
Practice Questions
- Write a function called
isPalindromeIgnoreCase()that checks if a given string is a palindrome, ignoring case sensitivity. - Modify the
isPalindrome()function to handle palindromes with spaces and special characters by removing them before comparison using regular expressions. - Implement a more efficient version of the
isPalindrome()function using recursion instead of loops. - Create a function called
findLongestPalindrome()that finds the longest palindrome within a given string, including spaces and special characters. - Write a function called
countVowelPalindromes()that counts the number of vowel-only palindromes in a given string. - Implement a function called
isPalindromeWithDuplicates()that checks if a given string is a palindrome, allowing duplicate characters. - Create a function called
findShortestPalindrome()that finds the shortest palindrome within a given string, including spaces and special characters. - Write a function called
isPalindromeWithSpacesAndPunctuation()that checks if a given string is a palindrome, handling spaces and punctuation marks as part of the comparison process. - Implement a function called
findAllPalindromes()that finds all palindromes within a given string, including spaces and special characters. - Write a function called
isPalindromeWithUnicode()that checks if a given string is a palindrome, handling unicode characters properly.
FAQ
- What if I want to check for palindromes that include numbers?: You can modify your function to only consider alphanumeric characters by replacing all non-alphanumeric characters with an empty string before comparison.
- How can I optimize the performance of my palindrome checking function?: One way is to stop the comparison as soon as a mismatch is found, instead of comparing the entire string. Another approach is to use regular expressions for character matching and removal of non-alphanumeric characters.
- Can I handle palindromes with spaces and special characters using a single function?: Yes, you can modify your function to handle these cases by removing non-alphanumeric characters before comparison. However, if you want to maintain the original string format (including spaces and special characters), consider creating separate functions for handling different types of palindromes.
- Is it possible to check for palindromes using built-in JavaScript methods?: While there are no built-in JavaScript methods specifically designed for checking palindromes, you can use a combination of string manipulation and comparison techniques to achieve the desired result.
- Can I handle palindromes with unicode characters properly?: Yes, you can modify your function to handle unicode characters by converting them to their ASCII equivalents before comparison. However, be aware that some unicode characters may not have direct ASCII equivalents and might require additional handling.
- What are some common palindromes in various languages?: Some examples of well-known palindromes include "Able was I ere I saw Elba" (English), "SOS" (International Morse Code), and "Madam, in Eden, I'm Adam" (English). Palindromes can be found in many languages and cultures, making them a fascinating topic for study.