The Code for ReverseMe
// Get the string from the page
// controller function
function getUserString() {
document.getElementById("alert").classList.add("invisible");
let userString = document.getElementById("userString").value;
if (userString.length > 1) {
let revString = reverseString(userString);
displayReversedString(revString);
} else {
alert("You must enter at least 2 characters to have it reversed!");
}
}
// Reverse the string
// logic function
function reverseString(userString) {
let revString = [];
// reverse a string using a for loop
for (let index = userString.length - 1; index >= 0; index--) {
revString += userString[index];
}
return revString;
}
// Display the reversed string to the user
// view function
function displayReversedString(revString) {
// write to the page
document.getElementById(
"msg"
).innerHTML = `${revString}`;
// show the alert box
document.getElementById("alert").classList.remove("invisible");
}
The code is structured into three functions.
getUserString
The getUserString function is responsible for getting the value from the page when the button is clicked. This function will also add the class "invisible" to the div element with a class of "alert" to ensure the message doesn't appear until the button is clicked. The other two functions are also called within this controller function. I also accounted for the cases when the user doesn't enter anything at all or only enters one character which cannot be reversed.
reverseString
This function takes in the userString from the getUserString function and reverses the string using a for a loop and returning the result in an array.
displayReversedString
This function takes in the revString array from the reverseString function and adds this string to the Dom. This function also removes the "invisible" class so the message appears on the page.