The Code:
// get the user input
function getString() {
document.getElementById("alert").classList.add("invisible");
//I had to use a variable per line which I'm not sure is correct but it wouldn't work without it.
//So uStr takes the user entered string.
let uStr = document.getElementById("userString").value;
//Then I convert it to lower case and make it lowStr
let lowStr = uStr.toLowerCase();
//Then finally I pump it back into userString like I had intended and strip the spaces and special characters.
let userString = lowStr.replace(/[^a-zA-Z0-9]/g, '');
//Here I call the reverse string function and use it on userString.
let revString = reverseString(userString);
//And here I use the displayString to display the now reversed string.
displayString(revString);
//Reverse it
function reverseString() {
let revString = [];
for (let index = userString.length - 1 ; index >= 0 ; index--) {
revString += userString[index];
}
return revString
}
//compare the two
// display it
function displayString() {
//Is it a palindrome?
if (revString == userString) {
document.getElementById("head-msg").innerHTML = `Well done! You entered a palindrome!`;
}
//If it isn't then...
else if (revString != userString) {
document.getElementById("head-msg").innerHTML = `Your entered string is not a palindrome.`
}
//Pump the result into the p tag.
document.getElementById("msg").innerHTML = `Reversed string is: ${revString}`;
//Turn the alert box back on
document.getElementById("alert").classList.remove("invisible");
}
}
The code is structured in one function.
Palindrome
My original comments are left in but basically I get a string, make it lower case if it isn't, then strip any special characters if there are any. After that I reverse that string using a backwards counting loop based on the length of the entered string. Then I compare the string to the original entered one, if they match I display a message and if they don't I display a different message along with the entered string.