The Code for REWIND
// Get the string from the page
// Controller function
function getValues(){
document.getElementById("alert").classList.add("invisible");
let userString = document.getElementById("userString").value;
let revString = reverseString(userString);
displayString(revString);
}
// Reverse the string
// Logic Function
function reverseString(userString){
let revString = "";
// reverse a string using a for loop
for(let i = userString.length -1; i >= 0; i--)
revString += userString[i];
return revString;
}
// Display the reversed string to the user
// View Function
function displayString(revString){
// Write to the page
document.getElementById("msg").innerHTML = `Your reversed string is: ${revString} `;
// Show the alert box
document.getElementById("alert").classList.remove("invisible");
}
The Code is structured in three functions.
getValues()
getValues is a controller function that gets the string value from the user and passes the string to the reverseString() function. The reversed string that is returned from that function is then sent to the displayString() function.
reverseString()
reverseString is a logic function that takes a parameter of the userString and returns it in reverse order. With the use of a for loop, we concatenate the characters from userString to the variable revString, by starting the for loop at the index of the last character and moving backwards through the string. We then return the string.
displayString()
displayString is a display function that receives a reversed string as a parameter and uses the elementID "msg" to pass this string as output to the user. We also remove the class "invisible" from the alert so that it can be seen by the user.