DocsHub
JavascriptIntermediate

Palindrome Checker

Build a palindrome checker that tells the user if a word or phrase reads the same forwards and backwards.

Palindrome Checker

Problem

Build a palindrome checker where the user types a word or phrase and the app instantly tells them whether it is a palindrome. The check should ignore spaces, punctuation, and letter casing.

Input: racecar
Output: ✅ "racecar" is a palindrome

Input: hello
Output: ❌ "hello" is not a palindrome

Input: A man a plan a canal Panama
Output: ✅ "A man a plan a canal Panama" is a palindrome

Input: Was it a car or a cat I saw
Output: ✅ "Was it a car or a cat I saw" is a palindrome

Input: (empty)
Output: (nothing shown)

Logic

  1. Select the input and result display elements
  2. Listen for the input event — check on every keystroke
  3. Read the value and check if it is empty
  4. Clean the string — lowercase, remove all non-letter and non-number characters
  5. Reverse the cleaned string
  6. Compare original cleaned string with reversed version
  7. Display the result with the original input text

Flow

yes no yes no User types input event fires Input empty? Hide result Lowercase the text Remove spaces and punctuation Reverse the cleaned string cleaned === reversed? Show palindrome message Show not palindrome message

HTML Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Palindrome Checker</title>
    <style>
      body {
        font-family: sans-serif;
        max-width: 480px;
        margin: 60px auto;
        padding: 0 20px;
      }

      input[type="text"] {
        width: 100%;
        padding: 12px;
        font-size: 1rem;
        border: 2px solid #ccc;
        border-radius: 8px;
        box-sizing: border-box;
        outline: none;
        margin-bottom: 16px;
      }

      input[type="text"]:focus {
        border-color: #555;
      }

      /* result box */
      #result {
        padding: 16px;
        border-radius: 8px;
        font-size: 1rem;
        font-weight: 500;
        display: none;
      }

      #result.success {
        background: #e6f9ee;
        color: #1a7a3f;
      }

      #result.failure {
        background: #fff0f0;
        color: #c0392b;
      }

      /* shows the cleaned version of the input */
      #cleaned {
        margin-top: 10px;
        font-size: 0.85rem;
        color: #888;
      }
    </style>
  </head>
  <body>
    <h1>Palindrome Checker</h1>

    <!-- user types here -->
    <input
      type="text"
      id="text-input"
      placeholder="Type a word or phrase..."
    />

    <!-- result shown here -->
    <div id="result">
      <span id="result-message"></span>
      <div id="cleaned"></div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

Solution

// Step 1 — select elements
const textInput = document.querySelector("#text-input");
const result = document.querySelector("#result");
const resultMessage = document.querySelector("#result-message");
const cleanedDisplay = document.querySelector("#cleaned");

// Step 2 — listen for input event — check on every keystroke
textInput.addEventListener("input", checkPalindrome);

function checkPalindrome() {
  const original = textInput.value;

  // Step 3 — hide result if input is empty
  if (original.trim() === "") {
    result.style.display = "none";
    return;
  }

  // Step 4 — clean the string
  // .toLowerCase() makes it case insensitive — "Racecar" becomes "racecar"
  // .replace(/[^a-z0-9]/g, "") removes everything that is not a letter or number
  // this handles spaces, commas, apostrophes, exclamation marks etc.
  const cleaned = original.toLowerCase().replace(/[^a-z0-9]/g, "");

  // Step 5 — reverse the cleaned string
  // split("") turns "racecar" into ["r","a","c","e","c","a","r"]
  // .reverse() flips the array to ["r","a","c","e","c","a","r"]
  // .join("") joins back into "racecar"
  const reversed = cleaned.split("").reverse().join("");

  // Step 6 — compare cleaned and reversed
  const isPalindrome = cleaned === reversed;

  // Step 7 — show result
  result.style.display = "block";

  if (isPalindrome) {
    result.className = "success";
    resultMessage.textContent = `✅ "${original.trim()}" is a palindrome`;
  } else {
    result.className = "failure";
    resultMessage.textContent = `❌ "${original.trim()}" is not a palindrome`;
  }

  // Step 8 — show the cleaned version so user understands what was compared
  cleanedDisplay.textContent = `Checked as: "${cleaned}"`;
}

Code Execution

Trace through typing "racecar":

StepCodeResult
OriginaltextInput.value"racecar"
Lowercase"racecar".toLowerCase()"racecar"
Clean.replace(/[^a-z0-9]/g, "")"racecar"
Split"racecar".split("")["r","a","c","e","c","a","r"]
Reverse.reverse()["r","a","c","e","c","a","r"]
Join.join("")"racecar"
Compare"racecar" === "racecar"true → palindrome ✅

Trace through typing "A man a plan a canal Panama":

StepCodeResult
Lowercase"a man a plan a canal panama"
Remove spaces.replace(/[^a-z0-9]/g, "")"amanaplanacanalpanama"
Reversed"amanaplanacanalpanama"
Compareboth are equaltrue → palindrome ✅

Trace through typing "hello":

StepCodeResult
Clean"hello"
Reversed"olleh"
Compare"hello" === "olleh"false → not a palindrome ❌

Output

Type "racecar"                         → ✅ "racecar" is a palindrome
Type "hello"                           → ❌ "hello" is not a palindrome
Type "A man a plan a canal Panama"     → ✅ "A man a plan a canal Panama" is a palindrome
Type "Was it a car or a cat I saw"     → ✅ "Was it a car or a cat I saw" is a palindrome
Empty input                            → (result hidden)

On this page