DEV Community

Cover image for 3 Ways to Reverse a String in JavaScript
Ahmad Adibzad
Ahmad Adibzad

Posted on • Edited on

3 Ways to Reverse a String in JavaScript

In this post, you’ll learn how to work with the string.split(), string.join() functions, and finally spread operator.

JavaScript is a fantastic programming language that allows us to write code differently. Reversing a string in JavaScript is simple. Assuming we have a string like “JavaScript forever” we want to reverse all the characters of that. Let’s get started to do it.

1. Using loops

In most programming languages, and for new developers, using loops is the first way they can do it. Since the string is an iterable type in JavaScript, you can iterate through each character from the last to the first.

const str = "JavaScript forever";
let reversed = "";

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

console.log(reversed); // reverof tpircSavaJ
Enter fullscreen mode Exit fullscreen mode

2. Using the split and join functions

In this way, you need to convert the string to an array. In JavaScript, you can split string characters into an array by using the split() function.

const str = "A text";

const arr = str.split('');  // ['A', ' ', 't', 'e', 'x', 't']

const reversedArr = arr.reverse(); // ['t', 'x', 'e', 't', ' ', 'A']

const reversedStr = reversedArr.join(''); // txet A

console.log(reversedStr); // txet A
Enter fullscreen mode Exit fullscreen mode

You can merge all the lines into one line:

const result = original.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

3. Using the spread operator

Still looking for an advanced way? The spread operator (...) allows us to create a real copy of an iterable value and put it into an object or array. So here, the spread operator can be used instead of the split() function to make an array from the string:

const str = "A text";
const arr = [...str]; // Creates an array of string characters
const reversedArr = arr.reverse();
const reversedStr = reversedArr.join('');
console.log(reversedStr); // txet A
Enter fullscreen mode Exit fullscreen mode

Of course, You can merge them all into one line:

const result = [...str].reverse().join('');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)