Today’s lesson is about finding Palindrome using client side JavaScript Programming. You can also find the same programs written in other technologies such as PHP, Python, Java etc in this website. Just search “Palindrome” in the search box to get them.
Here is the program:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Check Palindrome with JavaScript Program</title>
<style>
input{
padding: 10px;
}
</style>
<script>
function myFunction()
{
//get the value from textbox
var str = document.getElementById('txtbox').value;
//call checkPalindrome() and pass str
var result = checkPalindrome(str);
alert('The Entered String "'+str +'" is "'+result+'"');
}
function checkPalindrome(str)
{
var orignalStr;
//lowercase the string
str = str.toLowerCase();
//store the str in orignalStr for future use
orignalStr = str;
//reverse the entered string
str = str.split(''); //split the entered string
str = str.reverse(); //reverse the order
str = str.join(''); //then join the reverse order array values
var reverseStr = str;
//finally check both the Original string stored in orignalStr
//and reversed to find the palindrom
if(orignalStr == reverseStr){
return 'Palindrome'; // return "Palindrome" if true
}else{
return 'Not Palindrome';
}
}
</script>
</head>
<body>
<form action="http://www.tutorialsmade.com/" method="get">
<h3>JavaScript Palindrome Program from Tutorialsmade.com</h3>
<h4><a href="">Find the program here</a></h4>
<input type="text" id="txtbox" placeholder="Enter String" />
<input type="button" onclick="myFunction()" value="Check Palindrome" />
</form>
</body>
</html>Don’t you think the script is very big? But you can learn the below things from this script:
1. Reversing a String in JavaScript
2. How to Lower case a string in JavaScript
3. How to write a Function and return values in JavaScript
4. How to call a Function and other basic stuffs.
You can also see the demo here,
Some of the Palindrome words to check,
1. Madam
2. Civic
3. Mom
