Code-Alongs - Web Unit 2 Sprint 8

Code-Along: Palindrome Checker

In this code-along, you'll build a simple palindrome checker to practice string manipulation.

What Is a Palindrome?

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization.

Examples of palindromes include:

  • "racecar"
  • "A man, a plan, a canal, Panama"
  • "Madam, I'm Adam"
  • "Was it a car or a cat I saw?"

Palindrome Checking Algorithm

To check if a string is a palindrome, we need to:

  1. Remove all non-alphanumeric characters (spaces, punctuation, etc.)
  2. Convert all characters to lowercase
  3. Compare the string with its reverse

Here's a step-by-step implementation of a palindrome checker in JavaScript:

function isPalindrome(str) {
  // Step 1: Remove non-alphanumeric characters and convert to lowercase
  const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
  
  // Step 2: Compare with reverse
  const reversedStr = cleanStr.split('').reverse().join('');
  
  // Step 3: Return true if the string is the same as its reverse
  return cleanStr === reversedStr;
}

// Test the function
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("A man, a plan, a canal, Panama")); // true
console.log(isPalindrome("hello")); // false

Alternative Implementation: Two-Pointer Approach

Another common approach is to use two pointers, one starting from the beginning and one from the end of the string:

function isPalindromePointers(str) {
  // Step 1: Remove non-alphanumeric characters and convert to lowercase
  const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
  
  // Step 2: Use two pointers to compare characters
  let left = 0;
  let right = cleanStr.length - 1;
  
  while (left < right) {
    if (cleanStr[left] !== cleanStr[right]) {
      return false;
    }
    left++;
    right--;
  }
  
  return true;
}

// Test the function
console.log(isPalindromePointers("racecar")); // true
console.log(isPalindromePointers("A man, a plan, a canal, Panama")); // true
console.log(isPalindromePointers("hello")); // false