1

I'm trying to make a function that will check if a word is a palindrome. If the word is a palindrome it will return true else it will return false. "You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.

We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others."

My code is:

function palindrome(str) {
  str = str.toLowerCase().replace(/[^a-z]+/g,"");
  if (str === str.split("").reverse().join("")){
    return str;
  } else {
  return "This is not a palindrome";
  }
}

Could somebody tell me what is wrong with this code please?

Marc Freeman
  • 713
  • 2
  • 7
  • 30

3 Answers3

2

How about this solution.

function palindrome(str) {
  str = str.toLowerCase().replace(/[^a-z0-9]+/g,"");
  return str === str.split("").reverse().join("");
}

It strips non alpha-numeric characters, turns into lower case, and returns true | false

Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
  • Thank you! Could you explain why this works without the boolean logic? It's got me a bit stumped as the problem statement required me to return a "true" or "false" value depending on whether the word was a palindrome or not. – Marc Freeman Apr 08 '16 at 20:53
  • a comparison, i.e. `===` (or `==`) returns true or false. So the function compares parsed-input-string, with its reverse. If both are equal, it returns `true` – Unamata Sanatarai Apr 08 '16 at 20:55
  • Of course! I always forget that the equality and strict equality comparators compare two pieces of code and give a true or false statement in return. – Marc Freeman Apr 08 '16 at 21:09
1

"alphanumeric" means both alphabetical and numerical characters. Try something like this:

function isPalindrome(str) {
  str = str.toLowerCase().replace(/[^a-z0-9]+/g, '');

  return str === str.split('').reverse().join('');
}

isPalindrome('racecar')
// => true

isPalindrome('race car')
// => true

isPalindrome('race caR')
// => true
Josh Beam
  • 19,292
  • 3
  • 45
  • 68
0

It doesn't work because it always return a "true" because if not palindrome, then return a string, which evaluated as a boolean is true.

Fabricio
  • 3,248
  • 2
  • 16
  • 22