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:

<h2>Reverse text using JavaScript</h2>
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;
<input type="text" name="rev">
<input type="button" value="Reverse" onClick="reverse(this.form)">

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:


Share on Google+Share on Google+

JavaScript reverse text string

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: JavaScript reverse text string  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Tejas Dhamankar
May 22, 2012

Thanx Bro it works great. but i was searching for the code which can reverse it and store into a variable so i can check wheather the string is palindrome or not. B.T.W. Your Work Is Awesome. Thanks...