The Wayback Machine - https://web.archive.org/web/20240911030939/https://www.geeksforgeeks.org/reverse-a-string-in-javascript/
Open In App

Reverse a String in JavaScript

Last Updated : 29 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We have given an input string and the task is to reverse the input string in JavaScript. It is a very common question asked in a JavaScript interview. There are various methods to reverse a string in JavaScript, which are described below with examples.

reverse-a-string-in-js

Reverse a String in JavaScript

Examples:

Input: str = "GeeksforGeeks"
Output: "skeeGrofskeeG"

Input: str = "Hello"
Output: "olleH"

Reverse a String in JavaScript

There are the common approaches to reverse a string in JavaScript. These are:


1. Using reduce() and split() Methods

The split() method divides the string into an array of characters, and reduce() combines the characters in reverse order using the accumulator, effectively reversing the original string.

Example: The below code explains the use of the reduce and split method to reverse a string.

JavaScript
function reverseString(str){
    const reversedString = 
    str.split("").reduce((acc, char) => char + acc, "");
    console.log(reversedString);
}
reverseString("GeeksforGeeks");
reverseString("JavaScript");
reverseString("TypeScript");

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

2. Using split(), reverse() and join() Methods

The split() method divides the string into an array of characters, reverse() reverses the array, and join() combines the reversed characters into a new string, effectively reversing the original string.

Example: The below code uses the split(), reverse() and join() method to reverse a string in JavaScript.

javascript
// Function to reverse string
function reverseString(str) {
    const strRev =  str.split('').reverse().join('');
    console.log(strRev);
}

// Function call
reverseString("GeeksforGeeks");
reverseString("JavaScript");
reverseString("TypeScript");

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

3. Using Spread Operator

The spread operator(…) is used to spread the characters of the string str into individual elements. The reverse() method is then applied to reverse the order of the elements, and join() is used to combine the reversed elements back into a string. 

Example: The below code uses the spread operator to split the string into a series of characters and reverse it.

javascript
// Function to reverse string
function reverseString(str) {
    const strRev =  [...str].reverse().join("");
    console.log(strRev);
}

// Function call
reverseString("GeeksforGeeks");
reverseString("JavaScript");
reverseString("TypeScript");

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

4. Using Array.form() and reverse() Methods

The Array.from() is used to convert the string into an array of individual characters. The reverse() method is then applied to reverse the order of the elements in the array. Finally, the join() is used to combine the reversed elements back into a string.

Example: The below code example explains the above approach practically.

JavaScript
// Function to reverse string
function reverseString(str) {
    const strRev =  Array.from(str).reverse().join("");
    console.log(strRev);
}

// Function call
reverseString("GeeksforGeeks");
reverseString("JavaScript");
reverseString("TypeScript");

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

5. Using Spread Operator and reduce() method

The spread operator can be used to convert a string into an array of characters and use reduce() function in JavaScript to make a reverse string from an array by concatenating the string in the forward direction.

Example: This code implements the spread operator and the reduce method to reverse a string.

JavaScript
// Function to reverse string
function reverseString(str) {
    const strRev =  [...str].reduce((x, y) => y.concat(x));
    console.log(strRev);
}

// Function call
reverseString("GeeksforGeeks");
reverseString("JavaScript");
reverseString("TypeScript");

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

6. Using for Loop

The for loop is used to iterate through the characters of the string in reverse order. Starting from the last character (str.length – 1) and character pushed to the new reverse string one by one.

Example: The below code implements the for loop to reverse a string.

JavaScript
// Function to reverse string
function reverseString(str) {
    let strRev = "";
    for (let i = str.length - 1; i >= 0; i--) {
        strRev += str[i];
    }
    console.log(strRev);
}

// Function call
reverseString("GeeksforGeeks");
reverseString("JavaScript");
reverseString("TypeScript");

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

7. Using substring() and a Decrementing Index

The substring() method is used to extract the character at index i and append it to the reversed string. The index i is then decremented.

Example: The below code implements the substring() method to reverse the string.

JavaScript
// Function to reverse string
function reverseString(str) {
    let reversedStr = "";
    let i = str.length - 1;
    while (i >= 0) {
      reversedStr += str.substring(i, i + 1);
      i--;
    }
    console.log(reversedStr);
}

// Function call
reverseString("GeeksforGeeks");
reverseString("JavaScript");
reverseString("TypeScript");

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

8. Using Recursion

In a recursive approach a function repeatedly calls itself, taking the substring from the second character and concatenating it with the first character, until the base case is reached, reversing the string.

Example: This code implements the recursion to reverse a string in JavaScript.

JavaScript
function strReverse(str) {
    if (str === "") {
        return "";
    } else {
        return strReverse(str.substr(1)) + str.charAt(0);
    }
}
console.log(strReverse("GeeksforGeeks"));
console.log(strReverse("JavaScript"));
console.log(strReverse("TypeScript"));

Output
skeeGrofskeeG
tpircSavaJ
tpircSepyT

9. Using Stack

In this approach we use stack data structure. We iterate through each character of the input string and push it onto the stack. Then, we pop each character from the stack one by one and concatenate them to form the reversed string.

Example: This code uses the stack to reverse a string in JavaScript.

JavaScript
function reverseString(str) {
  const stack = [];
  // Push each character onto the stack
  for (let char of str) {
    stack.push(char);
  }
  // Pop each character from the stack to reverse the string
  let reversed = '';
  while (stack.length > 0) {
    reversed += stack.pop();
  }
  return reversed;
}

console.log(reverseString('GeeksForGeeks'));

Output
skeeGroFskeeG


Previous Article
Next Article

Similar Reads

JavaScript Reverse a string in place
JavaScript reverses a string in place refers to the process of flipping the order of characters within the string without using additional memory. It involves iterating through the string and swapping characters from both ends until reaching the middle. Reverse a string in place ExampleUsing the JavaScript split() methodJavaScript String split() Me
5 min read
JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
In this article, we have given a string and the task is to write a javascript program to reverse only the consonants of a string without affecting the other elements’ positions and printing the output in the console. Examples:Input: helloOutput: lelhoExplanation: h,l,l are consonants in the given string. After modifying the string their occurrences
6 min read
JavaScript Program to Reverse a String Using Recursion
We are given a string and the task is to reverse this string using the recursion technique in JavaScript such that a function calls itself again and again until it reaches the base case. Table of Content Using Basic RecursionUsing Tail RecursionUsing StackUsing Basic RecursionThe function recursively divides the string into smaller substrings until
2 min read
JavaScript Program to Reverse a String using Stack
Stack is the LIFO Data Structure that allows reversing a string by pushing characters onto the stack and popping them in reverse order to reconstruct the string. Below are the approaches to reversing a String using Stack. Table of Content Using Array as StackUsing Custom Stack ImplementationUsing Linked List as StackUsing Array as StackIn this appr
3 min read
Javascript Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Al
4 min read
PHP | Reverse a String
PHP serves us with many built-in methods which can be used to manipulate strings. In this article, we will learn about how to reverse a string using various methods available in PHP. Examples: Input : GeeksforGeeks Output : skeeGrofskeeG Input : 12485 Output : 58421 Below we have discussed about three basic and most commonly used methods of reversi
3 min read
How to reverse a string using filter in Vue.js ?
Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. Filters are a functionality provided
3 min read
Reverse a String in TypeScript
Reversing a string involves changing the order of its characters, so the last character becomes the first, and vice versa. In TypeScript, there are various methods to achieve this, depending on the developer's preference and the specific requirements of the task. Table of Content Using a LoopUsing Array Methods (reverse,split and join)Using reduceM
2 min read
JavaScript typedArray.reverse() Method
The typedArray.reverse() is an inbuilt function in JavaScript which is used to reverse the given typedArray elements i.e, first element becomes the last and vice versa. Syntax: typedArray.reverse(); Parameter: It does not accept any parameters. Return value: It returns the new reversed typedArray. Example: C/C++ Code // Creating some typedArrays wi
1 min read
How to use map() on an array in reverse order with JavaScript ?
Given a JavaScript array and the task is to apply the map() method but on the reverse of the array efficiently. Here are a few approaches discussed. If you don't want to change the original array then you can create a shallow copy of the array after that you can perform the task. Approaches to use array.map() in reverse order:Using JavaScript array
3 min read
Javascript Program to Print a given matrix in reverse spiral form
Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output:
3 min read
Sort an array in reverse order JavaScript
Sorting is a basic algorithm that is used in many programming languages. Most languages provide in-built methods to sort an array. In JavaScript we use the sort() method to sort an array in ascending order. To sort an array in the reverse order that is descending order there are no built-in methods to perform this task but we can combine different
3 min read
What is the use of reverse() method in JavaScript Arrays ?
The reverse() method in JavaScript is used to reverse the order of elements in an array. It modifies the original array and returns the reversed array. This means that the last element becomes the first, the second-to-last becomes the second, and so on. Example: Here, the reverse() the method is applied to the myArray, resulting in the original ord
1 min read
JavaScript Program to Print Reverse Floyd Pattern Triangle Pyramid
Printing a reverse Floyd pattern triangle pyramid involves outputting a series of numbers in descending order, forming a triangular shape with each row containing one less number than the previous row. The numbers are arranged in such a way that they form a right-angled triangle, reminiscent of Floyd's triangle, but in reverse order. Example: Input
2 min read
JavaScript Program to Reverse a Stack using Recursion
A stack is a collection of elements with two primary operations: push and pop. The push operation adds an element to the top of the stack, and the pop operation removes the top element. The stack follows the Last In, First Out (LIFO) principle. Table of Content Using recursionUsing Memoization with RecursionUsing recursionThe idea of the solution i
4 min read
JavaScript Program to Reverse a Linked List
A linked list is a data structure where elements are stored in nodes, and each node points to the next node in the sequence. Reversing a linked list involves changing the direction of the pointers, making the last node the new head and the head the new tail. Below are the approaches to reverse a linked list in JavaScript: Table of Content Reversing
3 min read
Reverse Words Starting with Particular Characters using JavaScript
We need to create a JavaScript function that reverses the order of all words in a given sentence that begins with a specific character. JavaScript allows us to reverse the words in a sentence that start with specific letters. Examples: Input: str= "I like to cook delicious meals every day"Character ch: "d"Output:"I like to cook suoiliced meals ever
4 min read
JavaScript Program to Count Reverse Pairs
Given an array, array [] of N integers, find the count of reverse pairs. A pair of indices (i, j) is said to be a reverse pair if both the following conditions are met: 0 <= i < j < N arr[i] > 2 * arr[j]Examples: Input: N = 6, arr = [3, 2, 4, 5, 1, 20]Output: 3Explanation: The reverse pairs are:(0, 4), arr[0] = 3 and arr[4] = 1, 3 >
3 min read
Reverse Only the Odd Length Words using JavaScript
Given a string containing words separated by spaces, our task is to reverse only the words with an odd length. The rest of the words remain unchanged. Example: Input: Hellow world how are you? Output: Hellow dlrow woh era you?Below are the approaches to Reverse only the odd-length words: Table of Content Using Split() Reverse() and Join() MethodsUs
3 min read
Reverse all the Words of Sentence JavaScript
Given a sentence, Our task is to reverse all the words in the sentence while maintaining their order. Example: Input: "Hello World" Output: "olleH dlroW"Below are the approaches to reverse all the words of sentence JavaScript: Table of Content Using Built-in FunctionsUsing Iterative ReversalUsing Built-in FunctionsIn this approach, The function rev
3 min read
How toReversed() method is different from reverse() method in JavaScript
In JavaScript, reverse() and toReversed() methods do the same job as reversing but toReversed() does not change the original array. The reverse() method changes the original array. Below we have explained both methods. Table of Content Reverse() MethodtoReversed() methodReverse() MethodThe reverse() method is a built-in method for arrays in JavaScr
2 min read
JavaScript Array reverse() Method
The JavaScript Array reverse() method reverses the order of the elements in an array in place. The first array element becomes the last, and the last element becomes the first, and so on. It modifies the original array and returns a reference to the reversed array. We can also use the Array.toReversed() which returns the new array with the elements
3 min read
Reverse an Array in Groups of Given Size in JavaScript
We are going to reverse a sub-array of a given size. We will be provided with an array and a random size for the sub-array to be reversed. There exist different variations of this problem. These are the following variations of reversing the array in groups of a given size: Table of Content Reverse the alternate groupsReverse at a given distanceReve
9 min read
JavaScript Program to Reverse Digits of a Number
Reversing the digits of a number means rearranging its digits in the opposite order. For instance, reversing 1234 gives 4321. In JavaScript, this is typically achieved by converting the number to a string, reversing the characters, and converting it back to a number, offering efficient manipulation. There are several methods that can be used to Rev
3 min read
Reverse an Array in JavaScript
Reversing an array is a common task in JavaScript, useful in various scenarios such as data manipulation, algorithm development, and UI rendering. This guide covers multiple methods to reverse an array effectively. Below are the approaches to reverse an array in JavaScript: Table of Content Using the reverse methodUsing for loopUsing unshift method
5 min read
Javascript Program For Merging Two Sorted Linked Lists Such That Merged List Is In Reverse Order
Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order). Examples: Input: a: 5->10->15->40 b: 2->3->20 Output: res: 40->20->15->10->5->3->2Input: a: NULL b: 2->3->20 Output: res: 20->3->2A Simple Solution is to do following. Rev
4 min read
Javascript Program For Printing Reverse Of A Linked List Without Actually Reversing
Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorithm: printReverse(head) 1. call print reverse for h
2 min read
Javascript Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
Javascript Program to Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
4 min read
Javascript Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Interview Recommended: Please solve it on “PRACTICE ” f
2 min read