Check for palindrome

Check for palindrome
0

#1

function palindrome(str) {
  // Good luck!
  strSplit = str.toLowerCase();
  strSplit = strSplit.split('');
  strSplit = strSplit.reverse();
  strSplit = strSplit.join('');
  strSplit = strSplit.replace( /\W|_/g, '');
  console.log(strSplit);
  if (str == strSplit){
    return true;
  }else {
    return false;
  }
}    


palindrome("racecar");

Whats wrong with my code?


#2

If the input is "_eye", strSplit is then "eye". When you do str == strSplit, you’re comparing "_eye" against "eye", so you get false.


#3

Another problem is the line below:

  if (str == strSplit){

Your strSplit is all lowercase but str could still have some uppercase letters in it. So

palindrome('Racecar') 

will return false in your code, but it should return true.


#4

Ok no I know what I’m doing wrong. Thanks.


#5
function palindrome(str) {
  // 1 remove non alphanumeric
  str == str.replace(/[\W_]/g, '');
  //2 turn to lower case
  str = str.toLowerCase();
  //3 reverse str 
  var store, swap;
  store = [];
  swap = [];
  
  for (i = 0; i < str.length; i++) {
    store[i] = str[i];
  }
  
  for (j = 0; j < str.length + 1; j++) {
    swap[j] = store[str.length - j];
  }
  
  swap.shift();
  swap = swap.join("");
  //4 compare str and reverse str
  if (swap == str) {
    return true;
  }
  else {
    return false;
  }
}



palindrome("-_Eye");

#6

Can someone tell me why this doesn’t work ?


#7

@tomokana You are doing an equality comparison instead of assignment here.
str == str.replace(/[\W_]/g, ‘’);

Replace == with = and it should work imo


#8

Sorry for late reply, when i log to freecodecamp it doesn’t log on the forum …

I’ve tryied with = and it works ! Thanks a lot :slight_smile:


#9

no worries- glad it worked!