JavaScript reverse text string

Ads
 

JavaScript reverse text string

This page discusses - JavaScript reverse text string

This page discusses - JavaScript reverse text string

JavaScript reverse text string

        

In this section, we are going to reverse the text string using JavaScript.

In the given example, we have created a function reverse() which is called by the button "Reverse". In the reverse() function, we have created two variables 'text' and 'str'. We initialize the variable  'text' to be empty. The form.rev.value takes the entered value of the text field and stores it into the variable 'str'. The for loop counts each character of the entered string and the JavaScript function substring() extracts the characters in the string with the starting index 'i' and ending index 'i+1'. Then the form.rev.value sets the reverse string to the variable text.

When you load the following code on the browser, you will get a text box and a button. On clicking the button after entering the text, you will get the reverse string in the same text box.

Here is the code:

<html>
<h2>Reverse text using JavaScript</h2>
<script>
function reverse(form) {
var text = "";
var str = form.rev.value;
for (i = 0; i <= str.length; i++)
text = str.substring(i, i+1) + text;
form.rev.value = text;
}
</script>
<form>
<input type="text" name="rev">
<input type="button" value="Reverse" onClick="reverse(this.form)">
</form>
</html>

Output will be displayed as:

Enter any text string inside the textbox:

On clicking the button, you will get the entered string in reverse order:

Download Source Code:

        

Ads

Ads