Why my «Check for Palindromes» if/else code isn't working?

Why my «Check for Palindromes» if/else code isn't working?
0

#1

Hello guys, I tried a million different ways to solve that problem but I just can’t go through with if/else statements.
My code looks like this:

 function palindrome(str) {
  var removeSpace=str.replace(" ","");
  var allLowerCase=removeSpace.toLowerCase();
  var splitStr=allLowerCase.split();
  var toArray=splitStr.join();
  if (toArray==toArray.reverse()) {
    return true;
  } else {
    return false; }
    }

Why isn’t it working? As mentioned, I tried different versions of identical code but again the same…


#2

I think you may have left out the quotation marks for var splitStr=allLowerCase.split();.
It didn’t split without the quotation marks.

Below works for some of the tests. Hope this helps.

function palindrome(str) {
  var removeSpace = str.replace(" ","");
  var allLowerCase = removeSpace.toLowerCase();
  var splitStr = allLowerCase.split("");
  var reverseArray = splitStr.reverse();
  
  console.log(splitStr, reverseArray);

  if (splitStr === reverseArray) {
    return true;
  }
  else {
    return false;
  }
}

#3

But again, we can’t pass the whole test… :confused:


#4

fyi, this only replaces the first ’ ’ it sees, you have to make some REGEX formula like so str.replace(/ /g,""). where g is global … or if you kinda dont get it yet with regex, this is more readable str.split(" “).join(”").toLowerCase();

For example,
palindrome(“not a palindrome”)
str.replace(" “,”") returns nota palindrome
str.replace(/ /g,"") returns notapalindrome
str.split(" “).join(”").toLowerCase(); returns notapalindrome

And for your code not not working,
Error: toArray.reverse() is not working
toArray is a string since you joined from an array. .reverve() can only be applied to arrays.

To learn debugging your code, use return more often, for example add ```return str`` at the begining of your function will return ‘eye’ in your result box so you can use them to check your other variables.


#5

Thanks for correcting my mistake. :smile: