The perfect way to check for a palindrome, in JavaScript

zamfir80

Razvan Zamfir

Posted on September 20, 2020

The perfect way to check for a palindrome, in JavaScript

Alt Text

First, let's clarify what a palindrome is.

According to Wikipedia "a palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward".

In the above definition, the word "reads" is key: a phrase like "Red rum, sir, is murder" is read, not written the same backward as forward. That is because of the punctuation and case.

The above is a clue for what the first two steps we need to take are: eliminate punctuation and spaces and force lower case.

After that, we can proceed with getting comparing the string to check with its reverse.

The function looks like this:

 const isPalindrome = (str) => {
  // Force to string
  // Eliminate punctuation and spaces
  // Force lower case
  // Split
  let arr = str.toString().replace(/[^A-Za-z0-9_]/g, "").toLowerCase().split('');

  // Join into one word
  let joined = arr.join('');

  // Reverse and join into one word
  let reverseJoined = arr.reverse().join('');

  //compare
  return joined == reverseJoined;
}
Enter fullscreen mode Exit fullscreen mode

After making sure our expression-to-check is a string, we use str.replace(/[^A-Za-z0-9_]/g, "") to eliminate punctuation and spaces and force lowercase with toLowerCase().

We need to make an array from the resulted string, so that we get the reverse of the string by reversing the array and then joining it into a string. This is the "original" array:

let arr = str.toString().replace(/[^A-Za-z0-9_]/g, "").toLowerCase().split('');
Enter fullscreen mode Exit fullscreen mode

The "original", lower case, no spaces, no punctuation string:

let joined = arr.join('');
Enter fullscreen mode Exit fullscreen mode

The reversed string:

let reverseJoined = arr.reverse().join('');
Enter fullscreen mode Exit fullscreen mode

Finally, the comparaison, that returns a Boolean:

return joined == reverseJoined;
Enter fullscreen mode Exit fullscreen mode

And with that we are done making a palindrome checker that works for words and phrases too. You can see it in action here.

💖 💪 🙅 🚩
zamfir80
Razvan Zamfir

Posted on September 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related