DEV Community

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

Posted on • Edited on

1

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more