The requirements for this task are that the code is returns a 'true' or 'false' for an input string. The string can be a simply word or a phrase. The other question does not address these needs. Please reopen and answer here. I am working on a function to check if a given string is a palindrome. My code seems to work for simple one-word palindromes but not for palindromes that feature capitalization or spaces.
function palindrome(str)
{
var palin = str.split("").reverse().join("");
if (palin === str){
return true;
} else {
return false;
}
}
palindrome("eye");//Succeeds
palindrome("Race car");//Fails
First the string is converted to lowercase. Also, the characters that are not the alphabet are removed. So the string comparison becomes a array, then invert it, and convert it to string again.
Step 1: str1.toLowerCase().replace(...) => "Race car" => "race car" => "racecar"
Step 2: str2.split("") => ["r","a","c","e","c","a","r"] => .reverse().join() => "racecar"
Result: str1 === str2
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]+/g,"");
return str === str.split("").reverse().join("")
}
alert(palindrome("eye")); //true
alert(palindrome("Race car")); //true
alert(palindrome("Madam, I'm Adam")); //true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With