Javascript Program To Check If A String Is Palindromes Not Returning False
Solution 1:
if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) {
is your problem.
In JavaScript, the sort
method updates the value of the variable you are sorting. So in your comparison, once both sort's have run, both end up with the same value (since the second sort, effectively overrides the first).
For example.
var a = [1,7,3];
a.sort();
console.log(a); // will print 1,3,7
Edit: had a quick test, I think eavidan's suggestion is probably the best one.
Edit2: Just put together a quick version of a hopefully working palindrome function :)
function palindrome(str) { return str.split("").reverse().join("") == str;}
Solution 2:
It is because string subtraction yields NaN
, which means both sorted arrays are the same as the original.
Even if you did convert to ASCII coding, you sort the entire string, then for instance the string abba
would be sorted front to back as aabb
and back to front as bbaa
. (edit: and also what Carl wrote about sort
changing the original array. Still - sort is not the way to go here)
What you should do is just reverse the string (using reverse
on the array) and compare.
Solution 3:
You might do as follows;
var isPalindrome = s => { var t = s.toLowerCase()
.replace(/\s+/g,"");
return [].slice.call(t)
.reverse()
.every((b,i) => b === t[i]);
};
console.log(isPalindrome("Was it a car or a cat I saw"));
console.log(isPalindrome("This is not a palindrome"));
Solution 4:
function pal()
{
var x=document.getElementById("a").value;
//input String
var y="";
//blank String
for (i=x.length-1;i>=0;i--)
//string run from backward
{
y=y+x[i];
//store string last to first one by one in blank string
}
if(x==y)
//compare blank and original string equal or not
{
console.log("Palindrome");
}
else
{
console.log("Not Palindrome ");
}
}
Post a Comment for "Javascript Program To Check If A String Is Palindromes Not Returning False"