The Code
function getValues() {
let userString = document.getElementById("userString").value;
let revString = reverseString(userString);
displayString(revString);
}
function reverseString(input) {
let revString = "";
for (let i = input.length - 1; i >= 0; i--) {
let letter = input[i];
revString = revString + letter;
}
return revString;
}
function displayString(output) {
document.getElementById("results").textContent = output;
let alertBox = document.getElementById("alert");
alertBox.classList.remove("invisible");
}
Code Explanation
This program allows users to input a string and see its reverse
version on the webpage. It is made up of three functions:
`getValues`
, `reverseString`
, and
`displayString`
. When the user clicks a button on the
page, `getValues`
is triggered and retrieves the value
of an input element with the ID "userString"
. It then
calls `reverseString`
with `userString`
as
an argument and stores the output in a variable named
`revString`
. Finally, it calls
`displayString`
with `revString`
as an
argument.
`reverseString`
is a function that takes a string as
input and returns the reversed version of the string. It initializes
an empty string called `revString`
and uses a for loop
to iterate through the input string in reverse order. For each
iteration, it retrieves the character at the current index and
appends it to `revString`
. Once the loop is finished,
it returns `revString`
. `displayString`
is
a function that accepts a string as input and displays it on the
webpage. It sets the text content of an element with the ID
"results"
to the input string and makes visible an
element with the ID "alert
" by removing the class
"invisible"
. In summary, this code provides a
straightforward example of how to manipulate strings and display
results on a webpage using JavaScript.