The Code
function getValues() {
let userString = document.getElementById('checkerInput').value;
let results = checkForPalindrome(userString);
displayResults(results);
}
function checkForPalindrome(userString) {
let revString = '';
userString = userString.toLowerCase();
let regex = /[^a-z0-9]/gi;
userString = userString.replace(regex, '');
for (let index = userString.length - 1; index >= 0; index = index - 1) {
let letter = userString[index];
revString = revString + letter;
}
let palindromeObj = {
isPalindrome: (revString == userString),
reversedString: revString
};
return palindromeObj;
}
function displayResults(results) {
let alertBox = document.getElementById('alert');
alertBox.classList.remove('invisible');
document.getElementById('msgReversed').textContent = `Your message reversed is: ${results.reversedString}`;
if (results.isPalindrome == true) {
alertBox.classList.remove('alert-danger');
document.getElementById('results').textContent = 'Great job! You entered a palindrome!';
alertBox.classList.add('alert-success');
} else {
alertBox.classList.remove('alert-success');
document.getElementById('results').textContent = 'Oops, this is not a palindrome';
alertBox.classList.add('alert-danger');
}
}
The code is structured in three functions...
Code Explained
The first function is getting the user input from the page, then later letting the results be
displayed. Then, the second function, checkForPalindrome is reversing the user input
and checking to see if it is the same as the original input. This code also changes all letters to
lowercase and removes any spaces or special characters so that they do not affect the final result.
After the for loop, an object is created to store both the true or false result of the loop and the
reversed version of the original
input. Finally, the displayResults function is finding the alert box in the HTML and
letting either a true or false result be displayed on the page when it returns that information to
the first function. The alert box will have a class of alert-success if true or a class
of alert-danger if false to make the display look better on the page.