Palindrome function is eating back slash

I’m grumpy with this challenge because my code is fine, it’s my regex that doesn’t work. In fact, I don’t even think it’s my regex.

This is my answer:

function palindrome(str) {
  var cleaned = str.toLowerCase();
  cleaned = cleaned.replace(/[.!,_\-\s]/g, "");
  
  var begin = 0;
  var end = cleaned.length - 1;
  var isPalindrome = false;
  
  while (begin < end) {
    if (cleaned.charAt(begin) === cleaned.charAt(end)) {
      isPalindrome = true;
    } else {
      isPalindrome = false;
      break;
    }
    begin++;
    end--;
  }
  return isPalindrome;
}

palindrome("eye");

The one test that is failing is: palindrome("0_0 (: /-\ :) 0-0") should return true.

When I debug that particular test string in jsfiddle, I get this:

function palindrome(str) {
  return str;
}

...

0_0 (: /- :) 0-0

The function is removing the back slash. WTF??! I’ve never seen that before. Otherwise, I’m happy with my code and just want to move on. Anyone know why there are gremlins in my function?

Your regex doesn’t match chars like parentheses, colons and slashes. You should add \(, ), \/. Then again, there are much more non-alphanumeric chars than that.

A better regex would be /\W|_/g or /[\W_]/g.

It’s not that the function removes the backslash. It’s that the backslash is a special character in strings. You need it to encode chars such as newlines ('\n'), tabs ('\t'), etc. Here JS parses the string as a backslash followed by a space ('\ '). It seems that backslash is ignored in Firefox Scratchpad and repl.it, though the challenge grader seems to ignore the space as well.

If you want to encode backslashes in strings, you’ll type '\\' (so to be pedantic, the input string "0_0 (: /-\ :) 0-0" should have been "0_0 (: /-\\ :) 0-0")

Thanks for answering.

So, the back slash is supposed to be kept in the string, not removed. My regex defines characters to be removed (therefore, I don’t need to escape the back slash, because I want to keep it).

The test itself is passing a string with a back slash and I have no control over this string, so I can’t rewrite it. Plus, it’s surrounded by quotes, which shouldn’t affect a back slash.

I tried your suggestion as my first answer: /[\W]/g and a bunch of tests failed because it seems the exercise wants certain characters and not others.

No, they should also be removed since they’re not alphanumeric.

Yes, you don’t have control over the test inputs (but that shouldn’t stop you from trying out some inputs you made up yourself). I was just explaining that a backslash has a special use in strings, and are not meant to be typed alone in code.

You forgot the underscore before the closing brace.

1 Like

Got it. Thank you. I removed the parentheses and the slashes. I was thinking “mirror”, not palindrome and completely overlooked that.