The Code
// get the text input from the page
function getValues() {
let message = document.getElementById('userInput').value;
if (message.length == 0) {
Swal.fire ({
icon: 'error',
backdrop: false,
title: 'Oops!',
text: 'Please enter a message to check for a palindrome'
});
} else {
let isPalindrome = checkForPalindrome(message);
displayResults(isPalindrome);
}
}
// reverse the message
function reverseMessage(userInput) { // if input = hello
let output = ''; // output = ['h', 'e', 'l', 'l', 'o']
for (let i = userInput.length-1; i >= 0; i--) {
output += userInput[i]
}
return output;
}
function checkForPalindrome(input) {
let regex = /[^a-zA-Z0-9]/g;
input = input.replace(regex, '');
input = input.toLowerCase();
let reversed = reverseMessage(input)
if (reversed === input) {
return true;
} else {
return false;
}
}
// display the reverse message
function displayResults(isPalindrome) {
document.getElementById('alert').classList.remove('invisible', 'alert-danger', 'alert-success');
if (isPalindrome == true) {
document.getElementById('msg').textContent = `Nice Job, that's a palindrome`;
document.getElementById('alert').classList.add('alert-success');
} else {
document.getElementById('msg').textContent = `Oh no, that's not a palindrome`;
document.getElementById('alert').classList.add('alert-danger');
}
}
getValues() is the main function that gets
called when you click the "Check" button. It first
retrieves the user's input from the userInput element
and further down the code,
checkForPalindrome() trims any extra spaces
as well as remove special characters. If the input is
empty, it displays a Sweet Alert error message.
If there is input, it checks if it's a palindrome using
the checkForPalindrome()
checkForPalindrome() removes
non-alphanumeric characters and converts the word to
lowercase. Then, it compares the characters from the
start and end of the word to determine if it's a
palindrome. If not, it returns false; otherwise, it
returns true.
displayResults() is responsible for showing
the message to the user with a green for success or red
for incorrect message.