Register Login

Reverse a String in JavaScript

Updated May 25, 2022

JavaScript is among the most popular languages for developing web apps and pages. The creator of JavaScript is Brendan Eich. He created it in 1995. It enables the creation of dynamic content, animating images, attractive web applications, and many more.

JavaScript provides stunning elements to the web pages and apps that increase user engagement. This article covers the topic of reversing a string in JavaScript with three different methods.

What is a string?

In programming, a string is a data type like integers and floats. A String usually contains plain text that resides between two double quotations. For example, "I like JavaScript". In an interview or as an exam question, one of the most frequently asked questions is how to reverse a string without using the inbuilt function or just applying recursion.

Reversing a String using Different Techniques:

Below are some of the ways to reverse a string:

Method 1: The manual approach:

Working of the below code:

  1. First, the program checks if the given string is empty, has one character, or is not of string type. It will return, “not valid”.
  2. If the string is not empty, a new array Rarray gets created to store the result.
  3. Then, the code iterates from the end of the array to the beginning and pushes each element into the new array (Rarray).
  4. Lastly, using the function join() to bind the elements in the array.

Code:

<!doctype html>
<html>
<head>
<meta name="robots" content="noindex,nofollow">
<meta charset="utf-8">
<title>Reverse string in Javascript</title>
<script> 
function Rstring(str){

	// Check input 
	if(!str || str.length < 2 || 
		typeof str!== 'string') { 
		return 'Not valid'; 
	} 

	// Create an empty array-Rarray 
	const Rarray = []; 
	const length = str.length - 1; 

	// Looping from the last element 
	for(let i = length; i >= 0; i--) { 
		Rarray.push(str[i]); 
	} 

	// Joining the elements using join() 
	return Rarray.join(''); 
}
</script>
</head>

<body>
<h1>Reverse string in Javascript</h1>
	<p><script>
		document.write("I like to code in JavaScript")
		document.write("<br>")
		document.write(Rstring("I like to code in JavaScript"));
		</script>
	</p>
</body>
</html>

Output:

Run Code

Method 2: using split() and reverse():

This method undergoes three simple steps:

  1. Split- The split() function divides the string into an array of characters.
  2. Reverse-  Reversing the separated elements using the function reverse().
  3. Join- Lastly, merging all the characters into the string with the function join().

Code:

<script>  
// Using the inbuilt functions to reverse the string
function Rstring(str) {
   return str.split('').reverse().join('')
}  
// Function gets called
document.write("JavaScript is easy to learn")
document.write("<br>")
document.write(Rstring("JavaScript is easy to learn"))
</script>

Output:

Run Code

Method 3: Using the spread operator with split() and join() methods:

This method is just a little different from the second method:

  1. It splits the string into an array of characters using the spread operator instead of the split() function.
  2. The code then reverses the characters with the help of the reverse() function.
  3. Lastly, merging all the characters using the function join().

Code:

<script>
	const Rstring = str => [...str].reverse().join(''); 
	//using the spread operator, and calling reverse(), join() function.
	document.write("Kindness is a great virtue")
	document.write("<br>")
	document.write( Rstring("Kindness is a great virtue") )
</script>

Output:

Run Code

Conclusion:

Often we require reversing a string in understanding long data, searching algorithms and competitive coding exams to check whether it’s a palindrome or a regular string. This article catered to some amazing ways to reverse the string using different methods and tactics.

Method 1 is comparatively more efficient because it uses less built-in methods than the second and third method. But there are various situations where the second and third methods are faster to write and use.


×