Write a Function That Checks if a String is a Palindrome

In the world of coding, a palindrome is a string that reads the same backward as forward, like the word "racecar" or the phrase "A man, a plan, a canal, Panama!" minus the punctuation and spaces, of course.

Let's dive into how we can implement a function in JavaScript to check if a given string is a palindrome. It's a great exercise for beginners and a common interview question, so pay attention! Plus, it's fun—like discovering your word is a secret agent, leading a double life.

Understanding Palindromes

Before we start coding, let's clarify what we mean by a palindrome in the context of this function. A palindrome is case-insensitive, and for simplicity, we'll ignore spaces and punctuation.

So, "Race car" is a palindrome because if you ignore the space and lowercase everything, it reads "racecar" forwards and backwards.

The Plan of Attack

We'll approach this problem step by step, starting with a straightforward solution and then exploring a more efficient approach. Our goal is to make this as simple as possible, so even if you're new to JavaScript, you'll be able to follow along.

Step 1: The Simple Approach

Let's start with the most straightforward approach: reversing the string and comparing it to the original.

function isPalindrome(str) {
  // Remove non-alphanumeric characters and convert to lowercase
  const cleanStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();

  // Reverse the cleaned string
  const reversedStr = cleanStr.split('').reverse().join('');

  // Check if the cleaned string is the same as its reversed version
  return cleanStr === reversedStr;
}

This function does the job, but let's break down what's happening here:

  1. We use replace with a regular expression to strip away any character that's not a letter or number, making our palindrome check more robust.

  2. We convert everything to lowercase to ensure our function is case-insensitive.

  3. We split the string into an array of characters, reverse that array, and then join it back into a string.

  4. Finally, we check if the cleaned and reversed string is the same as the cleaned original string.

Step 2: A More Efficient Approach

While the above method is simple and effective, it's not the most efficient. Why? Because it creates a new string and does quite a bit of extra work. Let's try an approach that compares characters from either end moving towards the center.

function isPalindromeEfficient(str) {
  str = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();

  let left = 0;
  let right = str.length - 1;

  while (left < right) {
    if (str[left] !== str[right]) {
      return false;
    }
    left++;
    right--;
  }

  return true;
}

This version avoids creating a reversed string and instead checks the characters starting from both ends, moving towards the center. It's more efficient, especially for longer strings, because it can potentially cut the number of comparisons in half.

Testing Our Functions

Let's put our functions to the test with some examples:

console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("A man, a plan, a canal, Panama!")); // true
console.log(isPalindrome("Hello, World!")); // false

console.log(isPalindromeEfficient("racecar")); // true
console.log(isPalindromeEfficient("A man, a plan, a canal, Panama!")); // true
console.log(isPalindromeEfficient("Hello, World!")); // false

Conclusion

Congratulations! You've just implemented two versions of a function to check if a string is a palindrome in JavaScript.

The first method is straightforward and beginner-friendly, while the second offers a more efficient approach for those looking to optimize their code.

Both are great starting points for understanding algorithmic thinking and string manipulation in JavaScript.

Remember, when it comes to coding, there's often more than one way to solve a problem. The key is understanding the trade-offs and choosing the right approach for your specific situation. Now, go forth and find more words living their best double lives!