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:
Tutorials
- Clear cookie example
- JavaScript getElementById innerHTML
- JavaScript getElementById Style
- Javascript Examples
- JavaScript add row dynamically to table
- New Page 1
- JavaScript Change link
- JavaScript Checkbox getElementById
- javascript clear textarea
- JavaScript Clock Timer
- JavaScript Cookies
- JavaScript Date Difference
- JavaScript duplicate string
- JavaScript Email Validation
- javascript focus input
- JavaScript get excel file data
- JavaScript getAttribute Href
- JavaScript getAttribute Style
- JavaScript getElementById div
- JavaScript getElementById Iframe
- JavaScript getElementById select
- JavaScript Hide Button
- JavaScript Hide Div
- JavaScript hide image
- JavaScript Hide Table Column
- JavaScript Hide Table Rows
- JavaScript Key Event
- JavaScript link
- JavaScript method location
- JavaScript move div
- JavaScript move file
- JavaScript move image
- JavaScript Navigate Back
- JavaScript navigate to page
- JavaScript Navigate to URL
- JavaScript indexOf substring
- JavaScript onkeypress event
- JavaScript Open file
- JavaScript Open link in new window
- JavaScript Open Modal Window