JavaScript

How to Reverse a String in JavaScript

Reversing an array is a very popular coding problem that is often asked as an interview question to beginner JavaScript devs. Sometimes the interviewers add certain restrictions, forcing you to come up with ingenious solutions.

In JavaScript, a string can be reversed by many different methods. In this post we will discuss the most creative and interesting methods for reversing a string.

How to Reverse a String Using Built-In Functions in JavaScript?

A combination of different JavaScript built-in Array and String functions can be used to reverse a string in JavaScript. In the following example let’s use the .split(), .reverse() and the .join() methods to reverse the string.

The .split() method will get the string as an argument and convert the whole string into an array, then the .reverse() method will reverse the whole array which will then be converted back into a string using the .join() method.

let greetings = "Welcome to Linux Hint";

let convertedArray = greetings.split("");  // Converts the String into an Array

let reversedArray = convertedArray.reverse(); // Reverses the Array

let reversedString = reversedArray.join(""); // Converts the Reversed Array back into a String

console.log(reversedString);

We can also chain all of these methods together:

let greetings = "Welcome to Linux Hint";

let reversedString = greetings.split("").reverse().join("");

console.log(reversedString);

How to Reverse a String With a For Loop in JavaScript

A decrementing for loop can also be used for reversing a string. To reverse an array using a for loop, we first need to create a new empty string. We can then use the decrementing for loop to put each character of the string into the new string in the reverse order.

var greetings = "Welcome to Linux Hint";

var reversedString = "";

for (let i = greetings.length-1; i >= 0; i--) {
  reversedString = reversedString + greetings[i];

}

console.log(reversedString);

Conclusion

String Reversing is another one of those coding challenges which every coding beginner must attempt. It is a simple algorithm which is often asked in entry level technical or screening interviews. You can take several different approaches to solving this problem.

In this post we learned to chain three built-in methods to reverse a string in JavaScript. Moreover we also learned to use a decrementing for loop to reverse a string.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.