The Code for StringFLip
//Get the string from the page
//Controller function
function getValue() {
document.getElementById("alert").classList.add("invisible");//Make alert invisible when getValue is called
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 index = userString.length - 1; index >=0; index--) {
revString += userString[index];
}
return revString;
}
//Display a message with the reversed string to the user
//View function
function displayString(revString) {
//Write to the page
document.getElementById("msg").innerHTML = `Your string reversed is: ${revString}`;
//Show the alert box
document.getElementById("alert").classList.remove("invisible");
}
The code is sctructured in three functions.
getValue
This function is responsible to fetch the string from the page field and call the other functions. It is the controller. Also, one important role here is to set the alert to invisible, so it doesn't stay on the screen after execution.
reverseString
The reverseString function is where the logic of this app is present. It uses a "for" loop to get the last index of a string and insert it in a new array backwards. Because of this it is possible to reverse a string.
displayString
Finally, this last function displays the reversed string in a alert box that pops up on the screen. It also removes the "invisible" class atribute so it can be seen by the user. It is the view function.