Reverse a string in JavaScript with example

 

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:

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

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

demo

 

 

 

1 thought on “Reverse a string in JavaScript with example”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top