Home Javascript Javascriptexamples JavaScript reverse text string

Related Tutorials


 
 

Share on Google+Share on Google+

JavaScript reverse text string

Advertisement
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:

        

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Discuss: JavaScript reverse text string  

Post your Comment


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

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...
DMCA.com