A palindrome is a word or sentence that’s spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

The Problem from code camp challenge

“You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes”.

My Solution

function palindrome(str){

//step 1. replace all unwanted characters with replace() function and convert the given text to lowercase using toLowerCase() function. Store the value in the variable "strReplaced"

var strReplaced = str.toLowerCase().replace(/\W|_/g, '');

//Step 2. Split the given text into a comma separated array using split(""), if you console.log the output using the given text you will get something like this:
Array [ "a", "m", "a", "n", "a", "p", "l", "a", "n", "a", .... ]

//step 3. reverse the array gotten from step 2 using the reverse() method which reverses an array in place. The first array element becomes the last and the last becomes the first and then use the join() method to convert it back to string.
var reverseStr = strReplaced.split("").reverse().join("");

//step 4. check if the text from step 3 and 4 is equal to the text that was stripped in step 1.
//if true it is a palindrome
if(reverseStr === strReplaced){
return true;
return false;


//call the function with a given string
palindrome("A man, a plan, a canal. Panama");

Checking for Palindromes in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: