0

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.

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

Kartikey
  • 4,516
  • 4
  • 15
  • 40
Jazz
  • 13
  • 2
  • there's no need for a form submit. A simple onclick handler on the button would be enough to execute the function. – Carl Verret May 27 '21 at 17:17

3 Answers3

0

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

var input = str.split('');
//                    ^^
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I've done this var input = str.split(''); Even after this i'm getting the same error as: Incorrect HTML Component / Attribute Fail 1 - Please check the JavaScript program logic Fail 2 - Please check the JavaScript program logic Summary of tests Test Case Failed – Jazz May 16 '21 at 11:38
0

After displaying the appropriate message through alert(), the page should not get redirected. alert(); is not used in this code

Sank
  • 1
0

you could have an even simpler code :

if( str == str.toLowerCase().split('').reverse().join(''))
Carl Verret
  • 576
  • 8
  • 21