Search code examples
javascriptpalindrome

Javascript simple palindrome function


 function palindrome(str) { // "Hello there"
   str.toLowerCase(); // "hello there"
   str = str.replace(/\s/g, ""); // "hellothere"
   var a = str;
   a.split("").reverse().join(""); // a = "erehtolleh"
   return (str === a); // "hellothere" === "erehtolleh"
 }

 alert(palindrome("123432"));

I passed non -palindromic value 123432 but it returns true value. Anyone know what's wrong with my palindrome function? Would really appreciate if someone can check my logic on it.


Solution

  • You need to assign value of a as its an return function

    function palindrome(str) {                       // "Hello there"
        str.toLowerCase();                               // "hello there"
        str = str.replace(/\s/g, "");                    // "hellothere"
        var a = str;                             
        a = a.split("").reverse().join("");                  // a = "erehtolleh"
        return (str === a);                             // "hellothere" == "erehtolleh"
    }
    
    
    alert(palindrome("malayalam"));