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.
Top comments (1)
I very much appreciate this article.