The Code
function getValues(){
// Grab User Input and assign it to variables for later use
let messageInput = document.getElementById("message").value;
let alertMessage = document.getElementById("alertMessage");
// Assign rewound to be the users input backwards
let rewound = rewind(messageInput)
let outputMessage = displayResults(messageInput, rewound, palindromeChecker(messageInput, rewound));
// Send data to the output message for the user to see
alertMessage.innerHTML = outputMessage;
}
function rewind(string) {
// Basic array reversal function
let rewound = "";
for (let i = string.length - 1; i >= 0; i--) {
// Iterate over the string backwards and push to a new array
rewound += string[i];
}
return rewound;
}
function palindromeChecker(input, rewound) {
// Check the input against the flipped version
// This is a regex filter to clear any punctuation and whitespace from the string
let cleaner = /[^a-z0-9]/gi;
// These next two lines normalize the text using the above
// regex and by making all letters lowercase
let inputClean = input.replace(cleaner, "").toLowerCase();
let rewoundClean = rewound.replace(cleaner, "").toLowerCase();
// Finally check if the cleaned input is the cleaned output
return (inputClean == rewoundClean);
}
function displayResults(input, output, palindrome) {
// Take the users input, flipped input, and whether it's
// a palindrome or not, and then return a message
// Make the alert box visible to the user
document.getElementById("alertMessage").style.opacity = 1;
// Use a ternary operator to swap between
// congratulations and consolation
let result = palindrome ? "Which is in fact a palindrome, congratulations!" : "Which I'm sorry to say isn't a palindrome"
// Build out the HTML to be displayed
let message = `<div>Your message, <i>${input}</i> reversed is <i>${output}</i><br>${result}</div>`
// Change alert colors based on success or failure
if (palindrome) {
document.getElementById("alertMessage").classList.add("alert-success")
document.getElementById("alertMessage").classList.remove("alert-danger")
} else {
document.getElementById("alertMessage").classList.add("alert-danger")
document.getElementById("alertMessage").classList.remove("alert-success")
}
return message;
}
getValues
This function takes the user input and prepares it for use in the rest of the functions, which it then calls.
rewind
This takes the user's input and flips it backwards. I kept it seperate for the sake of making it cleaner to then give back the user's reversed message.
palindromeChecker
This uses the reversed string from the rewind function, and the user's non-reversed input to verify if something is a palindrome. It starts by cleaning both strings using regex, and then making them lowercase before checking to see if they are equivalent strings.
displayResults
Here we take the output from all of the other functions and use them to construct a message for the user. We also stylize the alert window based on success or failure.