What am I doing wrong with the palindrome code?

What am I doing wrong with the palindrome code?
0.0 0

#1

Tell us what’s happening:

Your code so far


function reverseString(str) {
  var ignore= /[\W_]/g;
  var str2=str.toLowerCase().replace(ignore,'');
  var str3=str2.split("").reverse().join("");
  return str3;
}

function palindrome(str) {
 
var newString=reverseString(str);

  
  if (newString===str){
  return true;
  }
 
else {
  return false;
}
}
palindrome("race car");

Your browser information:

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

Link to the challenge:


#2

With your solution, str never changes from it’s original value, so when you make the comparison in your if statement (below), newString is “racecar” and str is still “race car”. Those are not going to be equal, so your function returns false.

if (newString===str) {

In your reverseString function you make the string you pass into it lowercase and replace all the non-word characters plus _ to blank strings. You need to do the same for the original str before the comparison is made.


#3

Hello,
The reason behind this:
your newString = racecar and str = race car (These two are not equal).

Try below code: (you have to bring str to the same state)

var ignore= /[\W_]/g;

function reverseString(str) {  
  var str2=str.toLowerCase().replace(ignore,'');
  var str3=str2.split("").reverse().join("");
  return str3;
}

function palindrome(str) {
 
  var newString=reverseString(str);
  str = str.toLowerCase().replace(ignore,'');
    
  if (newString===str){
  return true;
  }else {
  return false;
}
}


palindrome("race car");

#4

Thanks…I understood the mistake, Solved it…!:slightly_smiling_face: