Palindrome Check in javascript

 

Question:

Write a javascript function to check whether a word or a sentence is palindrome or not irrespective of case and spaces. Name the HTML file as palin.html.

Give appropriate alerts on click of a button name is “palinbtn”. Also provide a text box named “palin” which accepts the word / sentence. The screen should be as shown in the snapshot

Examples:

  • LiRiL – The entry is a palindrome.
  • Apple – The entry is not a palindrome.
  • Was it a cat I saw – The entry is a palindrome.
Note : Remove all white spaces from the input given and check for palindrome for the same input ignoring case.

CODE:

<html>
    <head>
        <script>
            function palindrome()
            {
                var str=document.getElementById("palin").value;
                var str=str.replace(/\s/g,"").toLowerCase();
                var input=str.split("");
                var output=input.reverse().join("");
                if(str==output) alert("The entry is a palindrome.");
                else alert("The entry is not a palindrome.");
            }
        </script>
    </head>
    <body>
        <form>
        Enter word/sentence to check for palindrome : <input type="text" name="palin" id="palin"><br>
        <input type="button" name="palinbtn" value="Check Palindrome" onclick="palindrome()">
        
        </form>
    </body>
</html>
Previous
Next Post »