Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a String is a Palindrome in JavaScript

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
like image 276
Austin Hansen Avatar asked Dec 06 '22 21:12

Austin Hansen


1 Answers

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
like image 200
Walter Chapilliquen - wZVanG Avatar answered Dec 25 '22 07:12

Walter Chapilliquen - wZVanG