The Code for RADAR
// Retrieve user input
// Controller function
function getString() {
// Alert box is hidden
document.getElementById("alert").classList.add("invisible");
// Get user string from page
let userInput = document.getElementById("userString").value;
if (userInput == "") {
alert("You did not enter a string");
} else {
// Check for a palindrome
let returnObj = checkForPalindrome(userInput);
// Display message to user
displayMessage(returnObj);
}
}
// Check if string is a palindrome
function checkForPalindrome(userInput) {
// Make all letters lowercase
userInput = userInput.toLowerCase();
// Remove all special characters
let regex = /[^a-z0-9]/gi;
userInput = userInput.replace(regex, "");
// Reverse the string
let reversedString = [];
let returnObj = {};
for (let i = userInput.length - 1; i >=0; i--) {
reversedString += userInput[i];
}
// Add correct msg and reversed properties to returnObj object
if (reversedString == userInput) {
returnObj.msg = "Well done, You have entered a palindrome!"
} else {
returnObj.msg = "Sorry, you did not enter a palindrome!"
}
returnObj.reversed = reversedString;
return returnObj;
}
// Display message to user
function displayMessage(returnObj) {
document.getElementById("result").innerHTML = returnObj.msg;
document.getElementById("msg").innerHTML = `Your phrase reversed is: ${returnObj.reversed}`;
document.getElementById("alert").classList.remove("invisible");
}
getString()
This function first ensures that the alert box in the HTML is hidden from the user. Then it assigns the string that was entered to the variable userInput. I have an if else statement after this that will throw an alert if the user does not enter anything. We then will call checkForPalindrome() with userInput as its argument and assign its returned value to the variable returnObj. Lastly, displayMessage() is called with returnObj as its argument.
checkForPalindrome()
First I use .toLowerCase to ensure there are no letter case differences that will throw off the string comparison. Then I use regex and .replace to remove any special characters or spaces since these don't need to be included in the comparison. Then I declare an empty array reversedString and an object returnObj. I wanted to use an object here so that I could return a message and the reversed string. Using a for loop that decrements i, I add each letter from userInput starting from the last index to the array reversedString. I then use conditional logic to compare it to userInput. It will add the correct message to returnObj depending on which condition is met. I also set returnObj.reversed to reversedString so that I can display that as well.
displayMessage()
This function is very straightforward. It sets all elements of the alert box in the HTML to the correct values from returnObj