So, recently I embarked on building the projects on the FreeCodeCamp JavaScript course, and I've decided to write about the steps I took to build them out as I proceed.
So, first, I created a palindrome identifier- a function that can be able to figure out if a word is a palindrome irrespective of whether it has non-alphanumeric characters or spaces.
First, what is a palindrome?
Palindrome are words or sentences that spelled the same way both forward and backward, ignoring punctuation, case, and spacing, this means that the words are exactly the same even when they are turned upside down. For instance, the word eye
looks the same even when turned both ways.
So, in the next few minutes, you'll be building along with me a function that returns true
if a word is palindrome and false
if it's not, ignoring spaces and alphanumeric characters.
Prerequisite
Before we proceed, you should have a knowledge of the following JavaScript methods:
split
replace
join
If you don't have an idea, take few minutes to read up this articles on split , reverse, replace and join methods.
Getting Started
Let's write our algorithm
- Remove spaces and alphanumeric characters from the string and store string in a variable.
- Reverse the string and also store in a variable.
- Compare the string and the reversed string.
- Return true if they are same and false if they are not equal.
Let's write our code
First,we'll define our function. Our function will be taking a string str
as argument
function palindrome(str){
}
Secondly, we have to eliminate spaces and non-alphanumeric characters from the string. We'll be using regex to fish out the non-alphanumeric characters and then replace it with '' (This is an easier way of removing elements from a string). We'll also convert the word to lowercase. You can choose to change yours to uppercase The aim of this is to keep all the alphabets on the same case to ease comparison.
function palindrome(str) {
let palindrom=str.replace(/[^0-9a-z]/gi, '').toLowerCase();
}
Having done this, let's create another variable reversed
where we'll store the reversed string. (We'll be reversing the variable palindrom
above)
function palindrome(str) {
let palindrom=str.replace(/[^0-9a-z]/gi, '').toLowerCase();
let reversed=palindrom.split("").reverse().join('');
}
Let's compare
function palindrome(str) {
let palindrom=str.replace(/[^0-9a-z]/gi, '').toLowerCase();
let reversed=palindrom.split("").reverse().join('');
if(reversed===palindrom){
return true;
}else return false;
}
palindrome(racecar)
Quite a short one, but yeah, we have a function here which can detect palindromes. I'd love to entertain feedback from you. Thanks for reading.