How to reverse a string in JavaScript

To reverse a string in JavaScript:

  1. Use the split() method to split a string into an array of substrings using a separator.
  2. Pass the array to the reverse() method to reverse the order of the elements in an array.
  3. Use the join() method to join all elements of an array into a string and returns the new string.
const str = 'john doe'

const tokens = str.split('')
// [ 'j', 'o', 'h', 'n', ' ', 'd', 'o', 'e']

const reversed = tokens.reverse()
// ['e', 'o', 'd', ' ', 'n', 'h', 'o', 'j']

const finalStr = reversed.join('')
console.log(finalStr)
// eod nhoj

The reverse() method reverses the order of the elements in an array. The first element becomes the last, and the last element becomes the first.

The join() method joins all elements of an array into a string and returns the new string.

You can also combine these three methods together and create a function as shown below:

const reverseStr = str => {
  return str.split('').reverse().join('')
}

reverseStr('hello world!')
// => !dlrow olleh

Reverse a string using a decrementing loop

Reversing a string using for loop might appear naive, but it works well. We can use decrementing (or even incrementing) loop to iterate over each character of the string and create a new reversed string:

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

reverseStr('hello world!')
// => !dlrow olleh

A modern for loop syntax using ES6 for...of:

const reverseStr = str => {
  let reversed = ''
  for (const c of str) {
    reversed = c + reversed
  }
  return reversed
}

Reverse a string using recursion

Recursion is another way to reverse a string in JavaScript. This approach involves two JavaScript functions: substr() and charAt().

The first method returns a substring of a string and the second method returns the specified character of a string.

const reverseStr = str => {
  return str ? reverseStr(str.substr(1)) + str[0] : str
}

reverseStr('hello world!')
// => !dlrow olleh

The number of times the recursive function is called, depends on the length of the string. It will become slow if the string is very long. So this is not a very good solution but still a way to solve the challenge.

Reverse a string using the reduce() method

Another rarely used approach to reverse a string in JavaScript is using the Array.reduce() function.

This method reduces the array to a single value. Since this function works for arrays, we first need to split the string into an array using the split() method.

const reverseStr = str => {
  return str.split('').reduce((r, c) => c + r, '')
}

reverseStr('hello world!')
// => !dlrow olleh

Summary

There are tons of different ways to reverse a string in JavaScript. In this tutorial, we have discussed 4 different approaches to solving the reverse string challenge:

  1. Using built-in JavaScript functions like split(), reverse(), and slice(). It is straightforward and perhaps the best approach.
  2. Using for loop to iterate over all characters of a string and create a new reversed string.
  3. Recursively convert the string into a substring until the empty string is reached, and then combine them to form a reversed string. It may become slow if the string is large.
  4. Splitting the string into an array and then reducing the array into a single value using the Array.reduce() function.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.