Reputation: 753
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
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
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
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