The Code For Backpedal
//Get the string from the page
//controller function
function getValue(){
document.getElementById("alert").classList.add("invisible");
let userString = document.getElementById("userString").value;
if (userString.length > 2 || userString.length === " " ) {
let revString = reverseString(userString);
displayString(revString);
}
else {
alert("You must enter three or more characters!");
}
}
//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 displayString(revString){
//write to the page
document.getElementById("msg").innerHTML = `Your reversed string is: ${revString}`;
//show the alert
document.getElementById("alert").classList.remove("invisible");
}
Description
The code can be broken down into three main functions:
1.) The Controller Function
The foundation for the JavaScript behavior is laid out by the controller function. The revString variable declaration is utilized to reverse the user's input. I used displayString(revString) to display the reversed string to the user. I also added an if-statement that ensures that the user enters a minimum of three characters to generate a reversed string. I could have also used regex for empty spaces instead of manually entering an empty string to the if-statement.
2.) The Logic Function
The reversal of the string that is entered by the user is executed by the logic function. First, I have defined the reverseString function so that it can hold a variable and a for-loop. This variable converts the entered string to an array. By doing this, we know how many characters the user entered. The characters are now identified by numerical values, which helps us create an instruction within JavaScript that reverses the input. The input is reversed by counting down from the largest to the smallest number in the array.
3.) The View Function
In the controller function, I had declared the revString variable. This variable is rendered in the view function. The reversed user input is written to a hidden alert. I used the classList of invisible to implement this functionality. The final step is to remove the invisible class to display the reversed string.