In: Computer Science
HTML
7.20
A palindrome is a number or a text phrase that reads the same backward and forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a script that reads in a five-digit integer and determines whether it’s a palindrome. If the number is not five digits long, display an alert dialog indicating the problem to the user. Allow the user to enter a new value after dismissing the alert dialog. [Hint: It’s possible to do this exercise with the techniques learned in this chapter. You’ll need to use both division and remainder operations to “pick off” each digit.]
Palindrome.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Five Digit
Palindrome</title>
<script
type="text/javascript">
function
Palindrome()
{
var start = prompt("Please enter a 5 digit
string to check whether it is palindrome or not: ",""); //Get the
inputted String
var palindrome = new Array(); //Empty array to
write the diffferent palindrome data to..
while(start.length !=5) //create a loop for
checking reelating to the length
{
alert("You didn't enter a 5
digit string! Please enter a 5 digit string!!");
start = prompt("Please enter
a 5 digit string to check whether it is palindrome or not: ","");
// Ask the user to re-enter the value again
} //end while
for(var i=0; i<=start.length-1 ;i++){ //loop
to pull off and isolate individual characters
palindrome[i] =
start.charAt(i); //Add each character to a new array
};
//Note that i did not check whether the numbers
were numeric...I just checked whether strings are matched or
not...!
if(palindrome[0] == palindrome[4])
{
//check whether first digit
equals to the fifth digit.
if(palindrome[1] ==
palindrome[3]) //check whether second digit equals to the fourth
digit.
{
document.write("The number you entered is:"+start+".");
document.write("<br> The number "+start+" is a
palindrome");
}
}
else //if 1 does not equals to 5 and 2 doesn't
equals to 4, then the string is not a palindrome!
{
document.write("The number
you entered is:"+start+".");
document.write("<br>
The number "+start+" is not a palindrome");
};
};
//end of main function
</script>
</head>
<body onload="Palindrome()">
<h1> Palindrome
Finder!</h1>
</body>
</html>
Output: