The Code
// entry point AKA Controller
function getValues() {
let userInput = document.getElementById('userInput').value;
let palindromeString = checkForPalindrome(userInput);
displayResults(palindromeString);
}
// logic function
// check to see if the input is a palindrome
function checkForPalindrome(userInput) {
let regex = /[\W_]/g;
let trimmedUserInput = userInput.toLowerCase().replace(regex, '');
let palindromeString = ''
for (let i = (trimmedUserInput.length - 1); i >= 0; i--) {
palindromeString += trimmedUserInput[i];
}
if (palindromeString != trimmedUserInput) {
// if it's not a palindrome, tell our user!
Swal.fire(
{
icon: 'error',
title: 'Oops!',
text: `"${userInput}" is not a Palindrome!`
}
);
} else {
return palindromeString;
}
}
// view function
function displayResults(palindromeString) {
if (palindromeString) {
document.getElementById('results').innerHTML =
`Your word or sentence reversed is: ${palindromeString}`;
document.getElementById('alert').classList.remove('invisible')
}
}
The code is structured in three functions
getValues()
This function grabs the input by the user and passes the input to the
checkForPalindrome(userInput)
function. It saves and passes the results to the
displayResults(palindromeString)
function.
checkForPalindrome(userInput)
This function first turns all the characters in the user input to lowercase, then it removes all non-alphanumerical characters by using a regular expression (regex), lastly, it cycles through the final input from back to front.
After the input has been reversed, the function then checks to see if the reversed input matches the original, broken down input the user gave. If the function confirms the input was a Palindrome, it passes the input to the the final function. If it confirms that the input was not a Palindrome, it will display an error.
displayResults(palindromeString)
This function displays the Palindrome in an alert box.