In this example, we will create a program using JavaScript and HTML to reverse a given string and display the output.
The JavaScript code will accept a string from a HTML textbox control and reverse the string and output the result to a H1 element to display.
The step to reverse the string is given below.
- Program accepts the input string.
- Split the string into an array of characters using
.split
function. - Reverse the array using .
reverse
function - Join the array of characters into a string using
.join
function. - Output the result to H1 tag.
JavaScript Code: Reverse a String
function reverseMyString() {
let str = document.getElementById("in").value;
let temp = str.split("");
let iter = temp.reverse();
str = iter.join('');
document.getElementById("out").innerHTML = str;
}
function MyClear(){
document.getElementById("in").value = "";
}
The function clear()
is to clear the textbox control. Each time the JavaScript want to access HTML data, it uses the id
attribute.
HTML and JavaScript Code: Reverse a String
<!DOCTYPE html>
<html>
<head>
<title>Reverse A String</title>
<meta charset="utf-8">
<style>
main{
width:40%;
padding:2%;
margin:10% auto;
background:rgba(50,115,220,0.3);
text-align:center;
}
#in{
padding:10px;
width:150px;
background:whitesmoke;
margin:auto;
}
button{
padding:10px;
margin:10px;
}
</style>
</head>
<body>
<main>
<h1 id="out">Output here</h1>
<input type="text" id="in" /><br/>
<button onclick="reverseMyString()">Reverse</button>
<button onclick="MyClear()">Clear</button>
</main>
<script>
function reverseMyString() {
let str = document.getElementById("in").value;
let temp = str.split("");
let iter = temp.reverse();
str = iter.join('');
document.getElementById("out").innerHTML = str;
}
function MyClear(){
document.getElementById("in").value = "";
}
</script>
</body>
</html>
In the program above, we have following HTML elements – a textbox, two buttons
, and H1 element
to output the result. The output to the program is given in the next section.