1

I have written following code to find out palindrome number/string.

<!doctype html>
<html>
<head>
<script>

function Palindrom() {
var rev="";
var str= document.getElementById("name1").value;


for ( var i=str.lenght; i>=0; i--)
{

var rev=rev + str.charAt(i);
}

if (str == rev)
{
alert ("Enter value is palindrome");
}

else
{alert ("Value is not palindrome");}

}

</script>
</head>
<body>
Enter String:<input type="text" name="Name" id="name1">
<button type="button" onclick="Palindrom();"> Check it</button>

</body>
</html>

However, it is giving the o/p of else statement even i am entering palindrome string in the box.. I don;t think there is something wrong. please correct the code and explain what was wrong. Thank you, sameer

sameer
  • 19
  • 5

4 Answers4

1

You should start reversing at str.length - 1 (because the strings are zero-indexed (that is, the first position in the string is 0 instead of 1 and, so, for a 5-character string, the last position is 4, not 5). Also, why not use some existing functions instead of reinventing the weel?

x = '1234'
y = x.split('').reverse().join('')
alert(y)
AdrianH
  • 76
  • 5
  • Doesn't work for all strings, e.g `aña` http://jsfiddle.net/nsp4d95y/ Here there is an explaination with fix: http://stackoverflow.com/a/16776621/1414562 – A. Wolff Feb 08 '15 at 12:39
  • I doubt the op needs to use this for an incredibly rich set of characters. Also, I expect the `for` not to work in that situation either. – AdrianH Feb 08 '15 at 12:46
  • That's true, none solution posted here work for special unicoded characters. For usual string, i prefer your answer over looping way, imho – A. Wolff Feb 08 '15 at 12:52
0

You have a typo in str.lenght

Also you should start your loop with str.length-1

Working example : http://jsbin.com/ponoro/2/edit

Example :

function Palindrom() {
var rev="";
var str= '12342554321';


for ( var i=str.length-1; i>=0; i--)
{

var rev=rev + str.charAt(i);
}
alert(rev)
if (str == rev)
{
alert ("Enter value is palindrome");
}

else
{alert ("Value is not palindrome");}

}
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • why should use str.length-1?? please explain.. I am beginner of javascript.. I think string index start with 0 and that's why we are separating one from total length.. – sameer Feb 08 '15 at 12:31
  • How many iteration would be with 3 chars ? `3&2&1&0` do you see the mistake ? – Royi Namir Feb 08 '15 at 12:32
0

Exactly str.length function returns the actual length of the array and not the offset i.e. speaking in a simple language the last index of the array is 1 minus the length of the array...

Meet Parekh
  • 12
  • 1
  • 4
0

Edit your typo ".length" ... or could also eliminate the loop if you wish.

function checkPalindrome(num){
    if(num == parseInt(num.toString().split('').reverse().join(''))){
        return true;
    }
    return false;
}
MarcJames
  • 189
  • 9