Check for Palindromes(0)

Check for Palindromes(0)
0

#1

Tell us what’s happening:
My function takes a string in as a parameter and returns true if it is a palindrome (a word which is read the same forward as backward). So far it returns true even if the parameter is not a palindrome. What have I done wrong?

Your code so far

function palindrome(str) 
{
  // Good luck!
  str.toLowerCase();
  str.replace(/ /, "");
  str.replace(/_/, "");
  var backStr = str.split();
  backStr.reverse();
  
  
  if(backStr.join("") === str)
    {
      return true;
    }
  
  else
    {
      return false;
    }
  
}


palindrome("nope");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:


#2

The problem is the following line:

 var backStr = str.split();

You did not specify a delimiter, so according to the documentation for split, if separator is omitted or does not occur in the string, the array returned contains one element consisting of the entire string.


#3

Okay, I made the change but now I think I have a problem with the use of my use of the replace() functions. Am I doing this correctly?

Here’s the code:


function palindrome(str) 
{
  // Good luck!
  str = str.toLowerCase();
  str = str.replace(/ /, "");
  str = str.replace(/_/, "");
  str = str.replace(/,/, "");
  str = str.replace(/./, "");
  var backStr = str.split("");
  backStr.reverse();
  
  
  if(backStr.join("") === str)
    {
      return true;
    }
  
  else
    {
      return false;
    }
  
}


palindrome("nope");

#4

The line below is not doing what you think it is:

  str = str.replace(/./, "");

The dot character is special when using regular expressions. The /./ matches any single character except the newline character, so it is replacing the first character of str with “”. If you want to match an actual dot, then you must use \.


#5

It didn’t work. Also, none of the other replace() functions are working.


#6

The replace functions are working, but by default they only replace the first match. You need to research “Regular expression flags”. You need to use one of them to match all instances.

You can also review the following FCC challenge:


#7

Oh! Thanks for your help