The Code for BACKTRACK
// Get string from the page
// Controller Function
function getValue() {
document.getElementById("alert").classList.add("invisible");
let userString = document.getElementById("userString").value;
let revString = reverseString(userString);
displayString(revString);
}
// Reverse string
// Logic Function
function reverseString(userString) {
let revString = [];
// Reverse string via for loop
for (let index = userString.length - 1; index >= 0; index--) {
revString += userString[index];
}
return revString;
}
// Display reversed string to user
// View Function
function displayString(revString) {
// Write message to page
document.getElementById("msg").innerHTML = `Your string reversed is: ${revString}`;
// Show alert box
document.getElementById("alert").classList.remove("invisible");
}
The Code as seen on the left is structured in three functions.
getValue
This is triggered when the "Reverse Me" button is clicked on the app. We hide the "alert" element as these are the results we don't want to display to the user on subsequent runs.
We then save the string input as a variable and pass that into our next function, reverseString.
reverseString
This function takes the string passed from the previous function and iterates through each character starting from the last and going backwards. Each iteration pushes the current character to a new array, revString, which will be returned as the reversed string to our controller function and passed as an argument to our next function, displayString.
displayString
Here we take our reversed string and apply it in a template literal to write the message to the page. We also need to remove the "invisible" class from our alert element so our reversed string can display!