JavaScript Reverse String – 4 Ways

In this tutorial I will talk about how you can reverse a string in JavaScript language.

This is a very popular question i.e. asked in interviews. There are many ways in which we can reverse a string. Here I will discuss different ways in which we can achieve this.

JavaScript Reverse String

Using Buitin Function

To reverse a string using built-in methods we have to chain some methods like join, split and reverse.

For this first, we need to convert the string into an array by using split method then after this, we have to reverse that array then join the array using join method. You can check the below example.

You can do this in one line as given below.

You can also create array instance by using Array.from inbuilt function.

First, use Array.from() to turn a string into an array, then Array.prototype.reverse() to reverse the array, and then Array.prototype.join() to make it back a string.

Using Loops

Loop is a process of repeating a block of code until a specific condition is met. So, we can reverse a string using for or while loop.

For loop:

While loop:

Using Recursion

Recursion is a process in which function called itself either directly or indirectly.

Using Ternary Operator

It is just a shorthand version of if conditional statement. In this operator, it requires at least 3 operands. You can increase the operators according to condition. Here I have used the substr() method and charAt method. They are inbuilt methods in javascript.

Substr method returns the characters in a string beginning at the specified location through the specified number of characters.

“hello”.substr(1); // “ello”

The charAt() method returns the specified character from a string.

“hello”.charAt(0); // “h”

I hope you got the ideas of how to reverse a string in JavaScript. Comment down below if you have queries or know any other way to do this.

Leave a Comment

Your email address will not be published. Required fields are marked *