The Code
function getValue() {
//hides the results alert
document.getElementById("alert").classList.add("invisible");
//get user input
let userString = document.getElementById("userString").value;
if (userString == "") {
Swal.fire({
icon: "error",
backdrop: false,
title: "Reviver",
text: "Input required!",
});
} else {
//reverse the user input
// let revString = ReverseAString(userString);
let revString = palindrome(userString);
//display the user input
displayString(revString);
}
}
function palindrome(revString) {
let allCheck = /[^A-Z0-9]/gi;
revString = revString.toLowerCase().replace(allCheck, "");
let len = revString.length;
for (let i = 0; i < len / 2; i++) {
if (revString[i] !== revString[len - 1 - i]) {
return "It is not a palindrome";
}
}
return `It is a Palindrome: ${revString}`;
}
//Display the String
function displayString(revString) {
if (revString.includes('not')){
document.getElementById("msg").innerHTML = `${revString}`;
document.getElementById("alert").classList.remove("invisible","alert-success");
document.getElementById("alert").classList.add("alert-danger");
}else{
document.getElementById("msg").innerHTML = `${revString}`;
document.getElementById("alert").classList.remove("invisible", "alert-danger");
document.getElementById("alert").classList.add("alert-success");
}
}
The code uses three functions.
getValue()
First I get the string the user has entered, if they have not entered a string it provokes an error, otherwise it calls the next function to check if its a palindrome, and finally it displays the results.
palindrome(revString)
This uses regex to check and make sure the word or phrase is the same casing and spacing across the board. Then it checks the string through a for loop and if statement.
displayString(revString)
Displays the results of the palindrome check.