How To Reverse A String In JavaScript

How To Reverse A String In JavaScript

3 Ways To Reverse A String In JavaScript

ยท

2 min read

In this short tutorial, we will look at 3 different ways of reversing a string in JavaScript.

Lets get right into it!

The First Method

In the first method, we will reverse a string by looping through each character and adding the character to the start of a new string so it reverses itself as the loop goes on.

This looks like this:

const reverseAString = str => {
    let reversedStr = ""
    for(let i in str) {
      const letter = str[i]
      reversedStr = letter + reversedStr
    }
    return reversedStr
}

We are simply creating a function called reverseAString that loops through each letter of the passed in str and adds it to the start of the reversedStr variable it creates. Finally, it returns the reversedStr variable which stores the reversed string.

This method is the longest of the methods we will be covering so I wouldn't recommend it but it does work.

The Array Method

In the array method, we will split the string into an array, reverse the array and then join the array back into a string.

In code:

const reverseAString = str => {
    return str.split("").reverse().join("")
}

This method is pretty self-explanatory, using the .split() method to split the string into an array, using the .reverse() method to reverse the array and then using the .join() method to join it back into a string.

This method is only one line of code (excluding creating the function) so I think its a great solution to reverse a string in JavaScript.

The Reduce Method

ES6 introduced various array methods that allow us to do cool stuff with arrays. One of which is the reduce method which essentially reduces an array down to a value.

We can use the .reduce() method to reverse a string:

const reverseAString = str => {
    return str.split("").reduce((reversedStr, letter) => letter + reversedStr, '');
}

This method simply splits the string into an array using the .split() method and then reverses it using the .reduce() method. To learn more about the reduce method check out my JavaScript High Order Array Methods article.

Take Away

We've covered 3 different methods of reversing a string in JavaScript in this article. I hope you've learned something useful.

๐Ÿ‘Œ Thanks for reading this article!

If you like what I do and would love to see more related content, follow me on my other social platforms:

Github: Blake-K-Yeboah

LinkedIn: Blake Yeboah

You can also show your support by buying me a coffee ๐Ÿ˜ƒ

Did you find this article valuable?

Support Blake Yeboah by becoming a sponsor. Any amount is appreciated!

ย