What's wrong with my code? (Palindrome challenge)

What's wrong with my code? (Palindrome challenge)
0

#1

Hi!

I am struggling a bit with the exercise called Check for Palindrome. Actually, I felt very quickly that I had the correct code, but it is not working. No matter what, it keeps coming back as true and not recognizing any of the false strings. What am I missing?

Here is what I have. I’m sure there is a simpler way to write this so I’m welcome to suggestions!

function palindrome(str) {
  // Good luck!
  var lcStr = str.toLowerCase();
  var splitStr = lcStr.split("");
  var revStr = splitStr.reverse();
if (revStr === splitStr){
  return true;
}
else {
  return false;
}

}

#2

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#3

.reverse() does these things: reverses the array with which it’s called, and returns a reference to that reversed array. When you do revStr === splitStr, you’re actually comparing the same array.


#4

You’re on the right track, but you’re not ignoring spaces, case and punctuation.
The challenge says for example that “A man, a plan, a canal. Panama” should return true.
You still have work to do.


#5

You can use slice method to return a shallow copy of the array.

var revStr = splitStr.slice().reverse(); // 1. create a copy of the array
                                        //  2. reverse the copy of the array
// rest of your code

#6

Ah yes! I forgot. I had tried achieving that by using /str/gi but it did not work the way I thought it was supposed to work. I must have done it wrong. I will work on it some more. Thank you for the reminder!


#7

You can’t compare arrays. [1,2,3] === [1,2,3] returns false. You have to join each of them if you want to compare.

If you google ‘remove non alpha-numeric characters from string javascript’, stack overflow has terse RegEx solution