JavaScript: Check if a String is a Palindrome

Problem Statement:

Write a JavaScript function that checks if a given string is a palindrome.

Solution Explanation:

  1. Convert the string to lowercase using .toLowerCase().
  2. Remove spaces using .replace(/\s/g, "") (optional, for handling phrases).
  3. Reverse the string using split("").reverse().join("").
  4. 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

Leave a Reply