Skip to content
Related Articles

Related Articles

Reverse a String in JavaScript
  • Difficulty Level : Basic
  • Last Updated : 16 Apr, 2019
GeeksforGeeks - Summer Carnival Banner

Given an input string and the task is to reverse the input string.

Examples:

Input: str = "Geeks for Geeks"
Output:  "skeeG rof skeeG"

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

There are many methods to reverse a string in JavaScript some of them are discussed below:

Method 1:

  • Check the input string that if given string is empty or just have one character or it is not of string type then it return “Not Valid string”.
  • If the above condition false create an array where we can store the result. Here revArray[] is the new array.
  • Loop through the array from the end to the beginning and push each and every item in the array revArray[].
  • Use join() prebuilt function in JavaScript to join the elements of an array into a string.

Example:






<script>
function ReverseString(str) {
  
    // Check input
    if(!str || str.length < 2 || 
            typeof str!== 'string') {
        return 'Not valid'
    }
      
    // Take empty array revArray
    const revArray = [];
    const length = str.length - 1;
      
    // Looping from the end
    for(let i = length; i >= 0; i--) {
        revArray.push(str[i]);
    }
      
    // Joining the array elements
    return revArray.join('');
}
  
document.write(ReverseString("Geeks for Geeks"))
</script>

Output:

skeeG rof skeeG

Method 2:

  • Use split() inbuilt function in JavaScript to split string into array of characters i.e. [ ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘, ‘f’, ‘o’, ‘r’, ‘ ‘, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’ ]
  • Use reverse() function in JavaScript to reversal the array of characters i.e. [ ‘s’, ‘k’, ‘e’, ‘e’, ‘G’, ‘ ‘, ‘r’, ‘o’, ‘f’, ‘ ‘, ‘s’, ‘k’, ‘e’, ‘e’, ‘G’ ]
  • Use join() function in JavaScript to join the elements of an array into a string.

Example:




<script>
  
// Function to reverse string
function ReverseString(str) {
   return str.split('').reverse().join('')
}
  
// Function call 
document.write(ReverseString("Geeks for Geeks"))
</script>

Output:

skeeG rof skeeG

Method 3:

  • Use spread operator instead of split() function to convert string into array of characters i.e. [ ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘, ‘f’, ‘o’, ‘r’, ‘ ‘, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’ ]. Learn more about the spread operator here Spread Operator
  • Use reverse() function in JavaScript to reversal the array of characters i.e. [ ‘s’, ‘k’, ‘e’, ‘e’, ‘G’, ‘ ‘, ‘r’, ‘o’, ‘f’, ‘ ‘, ‘s’, ‘k’, ‘e’, ‘e’, ‘G’ ]
  • Use join() function in JavaScript to join the elements of an array into a string.

Example:




<script>
const ReverseString = str => [...str].reverse().join('');
  
document.write(ReverseString("Geeks for Geeks"))
</script>

Output:

skeeG rof skeeG

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :