Problem Statement:
Write a JavaScript function that checks if a given string is a palindrome.
Solution Explanation:
- Convert the string to lowercase using
.toLowerCase()
. - Remove spaces using
.replace(/\s/g, "")
(optional, for handling phrases). - Reverse the string using
split("").reverse().join("")
. - Compare the original and reversed strings.
function isPalindrome(str) { str = str.toLowerCase().replace(/\s/g, ""); // Convert to lowercase and remove spaces return str === str.split("").reverse().join(""); // Compare original with reversed } // Test cases console.log(isPalindrome("madam")); // Output: true console.log(isPalindrome("racecar")); // Output: true console.log(isPalindrome("hello")); // Output: false console.log(isPalindrome("A man a plan a canal Panama")); // Output: true
Example Output:
Input: “madam” → Output: true
Input: “hello” → Output: false
Input: “A man a plan a canal Panama” → Output: true