user7039658
user7039658

Reputation:

I need help on this palindrome code

Here is the code I wrote on palindrome, no errors, but not working:

function palindrome(str) {
  // Good luck!
  x = 0;
  y = 0;
  for (x = 0; x == str.length; x++){ 
  str2 = str.reverse();
   for(y = 0; y == str2.length; y++){

    var firstChar = str.length[x];
    var lastChar = str2.length[y];
    if (firstChar === lastChar){
  return true;
  }
}
}
}
palindrome("eye");

I will appreciate some directions.

Upvotes: 0

Views: 80

Answers (1)

Geeky
Geeky

Reputation: 7496

var str="eye";
var strArray=str.split("");
var revStrArray=strArray.reverse();
var revString=revStrArray.join("");
if(revString===str)
  console.log("palindrome");

you are reinventing the wheel Try to make use of the library functions

var str="eye";

str==str.split("").reverse().join("")

str.split("")->splits it into Array as "e","y","e"
str.split("").reverse()->reverse works on array and makes it as "e","y","e"
join->makes again it as string ,now this will be "eye"

You need not run a for loop for this. Hope this helps

Upvotes: 1

Related Questions