Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods to Reverse a String in JavaScript
2.1.
split()
2.2.
reverse()
2.3.
join()
3.
Combining the Built-in Methods to Reverse a String in JavaScript
3.1.
JavaScript
3.2.
JavaScript
3.3.
JavaScript
3.4.
JavaScript
4.
Using a for Loop to Reverse a String in JavaScript
4.1.
JavaScript
5.
Using Recursion to Reverse a String in JavaScript
5.1.
JavaScript
6.
Reverse a String in JavaScript Using Conditional (Ternary) Operator
6.1.
JavaScript
7.
Reverse a String using Spread Operator
7.1.
Javascript
8.
Reverse a String using Array.form() and reverse() Methods
8.1.
Javascript
9.
Reverse a String using for Loop
9.1.
Javascript
10.
Reverse a String using substring() and a Decrementing Index
10.1.
Javascript
11.
Reverse a String using Recursion
11.1.
Javascript
12.
Frequently Asked Questions
12.1.
What is the fastest way to reverse string JavaScript?
12.2.
Can you use the reverse method on a string JavaScript?
12.3.
Which data structures are used to reverse a string?
13.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to Reverse a String in Javascript?

Author Sagar Mishra
1 upvote

Introduction

Are you curious about how to reverse a string in JavaScript? Well, you're in the right place! Reversing a string might seem like a tricky task, but with JavaScript, it's quite straightforward. In this blog, we'll explore simple methods and techniques to reverse any string using JavaScript. 

how to reverse a string in javascript

Let's start with the methods in JavaScript to reverse a string.

Methods to Reverse a String in JavaScript

split()

The split() method breaks down a string into smaller segments. Here, it separates the original string into its individual characters, arranging them within an array.

reverse()

The reverse() function changes the sequence of elements in an array by flipping their order. So, after the split() operation, the characters are in reverse order within the array.

join()

The join() method combines the elements of an array back into a string. It combines the reversed array of characters into a new string.

Combining the Built-in Methods to Reverse a String in JavaScript

In the "How to Reverse a String in Javascript" series, we will now learn the process using inbuilt functions.

We can use three methods in JS to reverse a given string. The methods are as follows.

  • split(): This method is used to break the string into single characters and store it in an array. The syntax of the split() method is.
  • JavaScript

JavaScript

string.split(separator, limit);
You can also try this code with Online Javascript Compiler
Run Code

 

  • reverse(): This method reverses the sequence of elements in the given array. The syntax of the reverse() method is.
  • JavaScript

JavaScript

array.reverse();
You can also try this code with Online Javascript Compiler
Run Code

 

  • join(): This method returns an array as a substring. The syntax of the join() method is.
  • JavaScript

JavaScript

array.join(separator);
You can also try this code with Online Javascript Compiler
Run Code

 

Let's check this out with the help of coding.

  • JavaScript

JavaScript

function stringReverse(str) {
  var stringSplit = str.split("");
  var reverseArr = stringSplit.reverse();
  var joinArr = reverseArr.join("");
  return joinArr;
}
console.log(stringReverse("CODINGNINJAS"));
You can also try this code with Online Javascript Compiler
Run Code

Output

SAJNINGNIDOC
You can also try this code with Online Javascript Compiler
Run Code

Using a for Loop to Reverse a String in JavaScript

The next topic in the "How to Reverse a String in Javascript" series is using for loop.

We can also use for loop for reversing a given string.

  • JavaScript

JavaScript

function reverseString(str) {
  let newStr = "";
  for (let i = str.length - 1; i >= 0; i--) {
     newStr += str[i];
  }
  return newStr;
}
var string = "CODINGNINJAS";

console.log(reverseString(string));
You can also try this code with Online Javascript Compiler
Run Code

Output

SAJNINGNIDOC
You can also try this code with Online Javascript Compiler
Run Code

 

Explanation:

  • First, we have created an empty string.
     
  • We will then use a decremented loop from the last char of the string to the first char of the string.
     
  • We will add the char from the string being iterated to the empty string during each iteration through the loop.
     
  • We will have our reversed string after the loop ends.

Using Recursion to Reverse a String in JavaScript

Our last topic in the "How to Reverse a String in Javascript" series is using Recursion. 

The process of the calling function itself until a specific condition is met is known as Recursion. Here we will use two methods that are as follows.

  • substr(): This method returns the characters in a string starting at the specified location.
     
  • charAt(): This method returns a specific character from the given string.
     

Let's check out How to Reverse a String in Javascript with the help of coding.

  • JavaScript

JavaScript

function reverseString(str) {
  if (str === "") return "";
  else return reverseString(str.substring(1)) + str.charAt(0);
}

var newString = "CODINGNINJAS";
console.log(reverseString(newString));
You can also try this code with Online Javascript Compiler
Run Code

Output

SAJNINGNIDOC
You can also try this code with Online Javascript Compiler
Run Code

Try it on an online javascript compiler.

Reverse a String in JavaScript Using Conditional (Ternary) Operator

Now, we will discuss how to reverse a string in JavaScript using conditional (Ternary) Operator.

  • JavaScript

JavaScript

function reverseString(s) {
return (s === '') ? '' : reverseString(s.substr(1)) + s.charAt(0);
}

s = "CodingNinjas";
document.write("Original String: "+s);
document.write("Reverse String: "+reverseString(s));
You can also try this code with Online Javascript Compiler
Run Code

Output

Original String: CodingNinjas
Reverse String: sajniNgnidoC

Explanation:

This code uses a recursive approach using the ternary operator to reverse a given string. The 'reverseString' function creates the reversed string by putting the first character at the end of the substring, leaving it out from the original spot. Then, the code uses this function on the string "CodingNinjas" and showcases the original and reversed strings using the document.write method.

Reverse a String using Spread Operator

The spread operator (...) can be used to split a string into individual characters, which can then be easily reversed and joined back together to form the reversed string.

  • Javascript

Javascript

function reverseString(str) {
return [...str].reverse().join('');
}

const originalString = "rahul";
const reversedString = reverseString(originalString);
console.log(reversedString);
You can also try this code with Online Javascript Compiler
Run Code

Output

luhar

 

In this example, the spread operator [...str] splits the string str into an array of characters, which is then reversed using the reverse() method. Finally, the join('') method joins the reversed array back into a string.

Reverse a String using Array.form() and reverse() Methods

The Array.from() method can be used to create an array from an iterable object, such as a string. Once the string is converted into an array, the reverse() method can be applied to reverse the array.

  • Javascript

Javascript

function reverseString(str) {
return Array.from(str).reverse().join('');
}

const originalString = "banana";
const reversedString = reverseString(originalString);
console.log(reversedString);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

ananab

This approach achieves the same result as using the spread operator but utilizes the Array.from() method instead.

Reverse a String using for Loop

Using a for loop, you can iterate over the characters of the string from the end to the beginning and concatenate them to form the reversed string.

  • Javascript

Javascript

function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}

const originalString = "rohit mehra";
const reversedString = reverseString(originalString);
console.log(reversedString);
You can also try this code with Online Javascript Compiler
Run Code

Output

arhem tihor

In this implementation, the for loop starts from the last character of the string (str.length - 1) and iterates backwards until the first character, appending each character to the reversed string.

Reverse a String using substring() and a Decrementing Index

Using the substring() method along with a decrementing index allows you to extract characters from the original string in reverse order and concatenate them to form the reversed string.

  • Javascript

Javascript

function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str.substring(i, i + 1);
}
return reversed;
}

const originalString = "hello";
const reversedString = reverseString(originalString);
console.log(reversedString);
You can also try this code with Online Javascript Compiler
Run Code

Output

olleh

Here, str.substring(i, i + 1) extracts each character from the string in reverse order, and they are concatenated to form the reversed string.

Reverse a String using Recursion

In recursion, the function calls itself with modified parameters until a base case is reached. For reversing a string recursively, the function chops off the last character and recursively calls itself with the remaining substring until the entire string is reversed.

  • Javascript

Javascript

function reverseString(str) {
if (str === "") {
return "";
} else {
return reverseString(str.substring(1)) + str.charAt(0);
}
}

const originalString = "eating";
const reversedString = reverseString(originalString);
console.log(reversedString);
You can also try this code with Online Javascript Compiler
Run Code

Output

gnitae

 

In this recursive approach, the function first checks if the string is empty (base case). If not, it calls itself with the substring starting from the second character and concatenates the first character at the end, effectively reversing the string.

Frequently Asked Questions

What is the fastest way to reverse string JavaScript?

The fastest way to flip a string in JavaScript is to use three methods: First, split the string into respective letters. Then, reverse those letters and put them back concurrently. It directly swaps characters for rapid reversal.

Can you use the reverse method on a string JavaScript?

In JavaScript, you can operate the reverse() method on an array to reverse its sequence. It effectively inverts the order of characters in the string. The array you use it on gets changed directly.

Which data structures are used to reverse a string?

Arrays or stacks are commonly used data structures to reverse a string. They allow the manipulation of individual elements, making it possible to change the order of characters.

Conclusion

We have discussed the topic of How to Reverse a String in Javascript in this article. In detail, we have seen various ways to reverse a string in Javascript. For example, using the inbuilt function, using For loop, and using recursion.

We hope this blog has helped you enhance your knowledge of "How to Reverse a String in Javascript." If you want to learn more, check out our articles.

And many more on our platform Coding Ninjas Studio.

Check out this problem - Reverse Nodes In K Group

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass