tadm123
tadm123

Reputation: 8793

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.

Upvotes: 2

Views: 777

Answers (2)

vijay
vijay

Reputation: 926

Try this , String is immuatble so you need to assign the reversed String to the variable or do compare with the original and reversed String like this.

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


alert(palindrome("12321"));
alert(palindrome("1232"));

Upvotes: 1

Vinod Louis
Vinod Louis

Reputation: 4876

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"));

Upvotes: 4

Related Questions