Marc Freeman
Marc Freeman

Reputation: 753

How to check if a string is a palindrome JavaScript [CLOSED!]

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?

Upvotes: 1

Views: 2057

Answers (3)

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6647

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

Upvotes: 2

Josh Beam
Josh Beam

Reputation: 19792

"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

Upvotes: 1

Fabricio
Fabricio

Reputation: 3297

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.

Upvotes: 0

Related Questions