Search code examples
javascriptpalindrome

Fail 1: Please check the JavaScript program logic while creating a Javascript Palindrome check


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.

Important Note:

  1. Remove all white spaces from the input given and check for palindrome of the same input ignoring case.
  2. After displaying the appropriate message through alert(), the page should not get redirected.
  3. Do not use 'let' or 'const' keywords. Instead, use 'var'.
  4. Use getElementById() or getElementsByName() to fetch value out of the HTML components.
  5. Make sure all tags and attributes are in lower case

Code:

<!DOCTYPE html>
<html>
  <body>
    //input from user using form
    <form onsubmit="return display();">
      Enter word/sentence to check for palindrome:<input
        type="text"
        name="palin"
        id="palin"
      /><br />
      <input type="submit" name="palinbtn" value="Check Palindrome" />
    </form>
    <script>
      function display() {
        //getting the value from textbox
        var str = document.getElementById("palin").value;
        //removing special char. and converting to lowercase
        var str = str.replace(/\s/g, "").toLowerCase();
        //removing whitespaces
        var input = str.split();
        //joining the reversed string
        var output = input.reverse().join("");
        if (str == output) {
          alert("The entry is a Palindrome.");
          return false;
        } else {
          alert("The entry is not a palindrome");
          return false;
        }
      }
    </script>
  </body>
</html>

Error in output


Solution

  • You need to split with an empty string to get all characters.

    var input = str.split('');
    //                    ^^