The Code for Back-Words
//get string from app page
//controller function
function getValue() {
document.getElementById("alert").classList.add("invisible");
let userString = document.getElementById("userString").value;
if (userString.length > 1) {
//call reverse string passing it the value of userString and setting that to revString
let backWords = reverseString(userString);
//calling displayString
displayString(backWords);
}
else {
alert("You must enter at least 2 characters to reverse your string!");
}
}
//Reverse string
//logic function
function reverseString(userString) {
//initialize empty array
let backWords = [];
//reverse a string using a for loop
for (let index = userString.length - 1; index >= 0; index--) {
backWords += userString[index];
}
return backWords;
}
//Display reversed string to user
//view function
function displayString(backWords) {
//write to page
document.getElementById("msg").innerHTML = `Your string reversed is: ${backWords}`;
//show alert box
document.getElementById("alert").classList.remove("invisible");
}
The Code is structured in three functions.
getValue
The getValue function gets user input from the app page. The function utilizes the getElementById to pull the userString value from the page. If the string length is less than one we set an alert, but if it more than one, we pass the value to the reverseString function. The function reverseString then returns an array that we set to the value backWords before we pass that same value to the displayString function.
reverseString
The reverseString function takes in a string parameter (userString). We create a variable backWords that holds an array. We then use a for loop to go through each index of the string from its last value to it's first, each time adding the indexes of userString to the array backWords.
displayString
The function displayString takes in the parameter backWords (the variable is an array that now holds the reversed string of the user's input). We use DOM manipulation to go after elements with id of "msg" in our HTML, and we set the contents of that p tag to our template literal. Then we remove the class list item "invisible" on all elements of "alert" to make the contents now visible to the user upon click!