Check for Palindromes
This blog explains my solution to the Check for Palindromes, a Bonfire exercise from Free Code Camp. The goal of this exercise is to figure out if a given string is a palindrome - a word, phrase, or a group of characters that reads the same backward or forward, and if it is, it will return true. Otherwise, it will return false. To write the code, you need to strip away punctuation and spaces, and make the string lowercase. This is achieved using replace() and toLowerCase() methods.
This tutorial is written for people who know a little about JavaScript but are not familiar with the replace() and toLowerCase() methods. You might be new to JavaScript or just curious about how these methods work.
Initial Problem
The initial code that’s given looks like this:
Solution
First of all, create a new object, called “stripStr”, and set it equivalent to the initial string that’s made lower case using the toLowerCase () method. Then add the replace() method to check for non-word characters, by using a regular expression we replace them with an empty strings. The final “g” acts as a global flag searching the entire string for this pattern. Here’s the command:
var stripStr = str.toLowerCase().replace(/\W|_/g, '');
In a recent exercise called Reverse a String Bonfire, we learned how to reverse characters in a string using the split(), reverse() and join() methods. We’ll use these same methods in order to reverse our initial string and return it no spaces. The code looks like -
stripStr.split('').reverse().join('')
Now let’s compare the newly stripped string with the one we reversed using an if/else statement. If stripStr is not identical to the reversed string, then it’s not a palindrome, and it returns false. If they are identical - meaning that both strings read the same forward and backward - then the code is a successful palindrome, and returns true.
Finished Code
It's a simple as that. As you can see the replace() method is useful for replacing non-alphabet and non-numerical characters. And the toLowerCase() method simply converts all characters to lowercase. These are two very handy methods to use, and in this case, they allowed us to easily identify palindromes.