MajhiRockzZ.me

moon indicating dark mode
sun indicating light mode

๐ŸŽ’ Different methods for String Reversal in JS

August 31, 2019

follow at github Twitter Follow my portfolio

In this article weโ€™re going to walk through some of the possible solution to reverse a given string in JavaScript. This might requires a little bit of knowledge of JavaScript in general.

Problem Statement

// Given a string, return a new string with the reversed
// order of characters
// --- Examples
// reverse('MajhiRockzZ!') === '!ZzkcoRihjaM'
// reverse('sumit') === 'timus'
// reverse('hello') === 'olleh'

Now essentially all we really want to do here is take a string that is provided as an argument. Reverse it and then return it from the function. And the last part is really important. Donโ€™t forget to return the string that gets reversed.

๐ŸŽˆ Method 1

Now the first solution that weโ€™re gonna start off with is by far the easiest one. However itโ€™s also not necessarily the most obvious one.

Explanation :

Code :

function reverse(str) {
const arr = str.split("")
arr.reverse()
return arr.join("")
}
reverse("MajhiRockzZ")

we can do a little bit of code cleanup to make this function a little bit more concise than it is.

function reverse(str) {
return str
.split("")
.reverse()
.join("")
}
reverse("MajhiRockzZ")

๐ŸŽ Method 2

In the previous method we put together one very straightforward solution for reversing a string. But what if we want the solution without using the reverse helper. obviously if you know this thing exists it really makes the question quite easy and quite straightforward. So in this section weโ€™re going to look at an alternative solution thatโ€™s a little bit more manual work.

Explanation :

Code :

function reverse(str) {
let reversed = ""
for (let character of str) {
reversed = character + reversed
}
return reversed
}
reverse("sumit")

So this is one possible solution.


๐Ÿ• Method 3

We have now put together two possible solutions to the string reversal problem. In addition Iโ€™m going to show you one more complicated ways of solving this problem. So in this last solution we are going to use a very complicated little array helper. So letโ€™s give this last solution a shot.

Code :

function reverse(str) {
return str.split("").reduce((reversed, character) => {
return character + reversed
}, "")
}
reverse("hello")

The last thing that i would probably do here is to simplify some of the syntax a little bit.

function reverse(str) {
return str.split("").reduce((rev, char) => char + rev, "")
}
reverse("hello")

So any three of these solutions works 100 percent just fine. And of course, there are other solutions out there that might be better than these three.

Resource

๐Ÿ“š Learn JavaScript and jQuery, Ajax, APIs & JSON

JavaScript and JQuery