Palindromes exercise

The code doesn’t pass. Here is my code ,i;ll explain the logic(my logic) after i post it:

function palindrome(str) {
  var  x = str.split('').reverse().join("");
  var y = x.replace(/\s+/g, '');
  var palindr = y.toLowerCase();
  if ( palindr == str){ 
  return true;
  } 
  else {
    return false;
  }
}
palindrome("eye");

So my logic is ,take the word passed into it,turn it into an array turn it backwards then put it together back into a string,then,check if the thing backwards is the same as the word passed in there. Why it doesn’t work is my question or what different approach should i take?

You’re checking if a copy of the string that has been reversed, lowercased and had all spaces removed is the same as the original string. But the task is not asking you to check if it is the same as the original string. Think about this: it will only work for very simple palindromes (“eye”). But “Eye” is a palindrome aswell. And “A man, a plan, a canal, Panama” is a palindrome as well. Also as far as I can remember, this particular task accepts numbers but ignores other non-letter characters: I think the rules of it would allow something like “&-+e!!!1???#)_(-+#e” as a palindrome

1 Like
function palindrome(str) {
  var  x = str.split('').reverse().join('');
  var y = x.replace(/[\W_]/g, '');
  var palindr = y.toLowerCase();
  if ( palindr == str){ 
  return true;
  } 
  else {
    return false;
  }
}

palindrome("eye");

changed it like that,this way only a-z chars are allowed. even their solution to the quiz use the “/[\W_]/g,” in replace,so why would their work and not mine .
their solution is

function palindrome(str) {
  return str.replace(/[\W_]/g, '').toLowerCase() ===
         str.replace(/[\W_]/g, '').toLowerCase().split('').reverse().join('');
}

Again, the task does not require you to compare the original string to the reversed version, but that is what you are doing and it wont work

I see.Any piece of advice?

“Eye” is a palindrome. Your version will try to compare the original string “Eye” to “eye” so it will fail.

“A man, a plan, a canal, Panama” will compare to “amanaplanacanalpanama” so will fail.