The Code for Level


                        //get string from the page
//controller

function getString() {

    document.getElementById("alert").classList.add("visible");//Make alert invisible when getValue is called

    let userString = document.getElementById("userString").value;

    let returnObj = checkPalindrome(userString);

    displayMessage(returnObj);

}

//check if its a palindrome
//logic
function checkPalindrome(palindrome) {
    
     //make all lower case letters
     palindrome = palindrome.toLowerCase();

    //first remove special characters 
    let regex = /[^a-z0-9]/gi;
    palindrome = palindrome.replace(regex,"");

    let revString = [];

    let returnObj = {};

    for (let index = palindrome.length-1; index >= 0; index--) {

        revString += palindrome[index];

    }

    if (revString == palindrome) {

        returnObj.msg = "Well Done! You entered a palindrome!";
    }else {
            returnObj.msg = "Sorry, you did not enter a palindrome!";
        }
    
        returnObj.reversed = revString;

        return returnObj;
    
    }
   

//display
//view
function displayMessage(returnObj){

    document.getElementById("alertHeader").innerHTML = returnObj.msg;
    document.getElementById("msg").innerHTML = `Your phrase reversed is: ${returnObj.reversed}`;
    document.getElementById("alert").classList.remove("invisible");

}

                    
                

The code is sctructured in Three functions.

getString()

This function is the starting point for the program. It gets the user's input from a text field on a webpage. The function then calls checkPalindrome() to determine if the entered string is a palindrome and displayMessage() to show the result on the webpage.

checkPalindrome()

This function takes a string as input and checks whether it is a palindrome. It performs the following steps:

  • Converts the input string to lowercase to handle case insensitivity.
  • Removes any special characters and spaces from the string using a regular expression.
  • Creates a reversed version of the cleaned string.
  • Compares the reversed string with the original to determine if it's a palindrome.
  • Constructs and returns an object (returnObj) containing a message indicating if the input is a palindrome and the reversed version of the string.
displayMessage()

This function takes the returnObj as input and displays the result on the webpage. It modifies the content of certain HTML elements to show whether the input is a palindrome or not, along with the reversed version of the string.