Today you are going to learn how to reverse a string in JavaScript using reverse() function with an example script.
reverse() is a JavaScript function which alters the order of the elements in an array, so if you want to reverse a string, first you have to convert that string into an array.
Three JavaScript function you need to use for this:
1. split()
2. reverse()
3. join()
Here is the script:
1 2 3 4 5 6 7 |
//reverse function function reverseString( str ){ str = str.split(''); //string to array str = str.reverse(); //reverse the order str = str.join(''); //then join the reverse order values return str; } |
So, basically split the string into array values, reverse the order and then join the array values, you have your result.
Here is an example usage of the above script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<html> <head> <script> //usage function doReverse(){ var str = document.getElementById( 'mystring' ).value; alert( "" + reverseString( str ) ); } //reverse function function reverseString( str ){ str = str.split(''); //split the entered string str = str.reverse(); //reverse the order str = str.join(''); //then join the reverse order array values return str; } </script> </head> <body> <h3>Reverse a String in JavaScript - <a href="http://www.tutorialsmade.com/reverse-string-javascript-example/">Tutorialsmade.com</a></h3> <input type="text" id="mystring" value="spider" /> <button id="btn" onClick="doReverse()" >Reverse</button> </body> </html> |
And finally a demo link to test it:
Hi,
How can we reverse the string like “Hello World” to “World Hello” ?
Thank you