The perfect way to check for a palindrome, in JavaScript
Razvan Zamfir
Posted on September 20, 2020
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;
}
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('');
The "original", lower case, no spaces, no punctuation string:
let joined = arr.join('');
The reversed string:
let reverseJoined = arr.reverse().join('');
Finally, the comparaison, that returns a Boolean:
return joined == reverseJoined;
And with that we are done making a palindrome checker that works for words and phrases too. You can see it in action here.
Posted on September 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.