Palindrome Algorithm

Hi everyone!

I am stuck on this algorithm. I took a peek at the answer and updates my regex to match it, but I am still unsure why my solution isn’t performing. Can someone give me a hint or suggestion?

function palindrome(str) {
  
  var palindrome="";
  
  for (var i = str.length-1; i >= 0; i--) {
    palindrome += str[i];
  }
  
    palindrome.replace(/[\W_]/g, "");
    palindrome.toLowerCase();
  
    str.replace(/[\W_]/g, "");
    str.toLowerCase();
  
  if (palindrome === str) {
    return true;
  } else {
    return false;
  }
}



palindrome("_hannah");

seems to be working for the test case your provided, as well as passing it ‘hannah’.

what test cases is it failing on?

Hi,

It wasn’t working for “_eye” or “_hannah” as both are supposed to return true. The replace prototype is supposed to replace all special characters.

Best,
Silas

If you place some debug code before your if statement:

  console.log(str)
  console.log(palindrome)

You’ll see the problem - your non-alphanum chars are not being removed.

The replace method does not change the original string but returns the new new string, so you need:

palindrome = palindrome.replace(/[\W_]/g, "");

and do the same thing for str.

There are some other optimizations. For example, why replace and lowercase twice? Before creating palindrome you can do it to the original:

    str = str.replace(/[\W_]/g, "").toLowerCase();

Also, instead of:

  if (palindrome === str) {
    return true;
  } else {
    return false;
  }

you can use:

return palindrome === str;

Hi Kevin,

Thanks for the tips.

-Silas