1

I'm attempting to find a solution to check for a palindrome. When I use the code:

function palindrome(str) {
  var checkSpecial = str.replace(/[^A-Za-z0-9]/g, '');
  var checkPalindrome = str.split('').reverse().join('');
  return checkSpecial == checkPalindrome;
}
console.log(palindrome("_eye")); // false

It returns false. I can't seem to get non-alphanumeric characters to remove.

Andy
  • 45
  • 3
  • 12
  • Neither comment makes sense, the result of replace is bring assigned to the string being checked, and the question is not adding to solve it only using a regular expression. The above code should work... – Ruan Mendes Aug 03 '16 at 02:31

2 Answers2

5

Well, of course "eye" !== "eye_". You probably want

function palindrome(str) {
  var checkSpecial = str.replace(/[^A-Za-z0-9]/g, '');
  var checkPalindrome = checkSpecial.split('').reverse().join('');
  return checkSpecial == checkPalindrome;
}
console.log(palindrome("_eye")); // true
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • I understand where I went wrong. Thank you for your help with that. I'm new to posting on Stack Overflow and I think its pretty cool how quickly others can identify the problem and correct it so quickly. – Andy Aug 03 '16 at 02:51
  • Good to hear. Don't forget to accept the answer! – Owen Aug 03 '16 at 02:55
0

You need to remove the special characters from both strings. Note that you are not trying to use regex to test for palindromes (which is good because that's impossible). Fixed version:

function palindrome(str) {
  var checkSpecial = str.replace(/[^A-Za-z0-9]/g, '');
  var checkPalindrome = checkSpecial.split('').reverse().join('');
  return checkSpecial == checkPalindrome;
}
console.log(palindrome("_eye")); // false
Owen
  • 1,527
  • 11
  • 14