How to Reverse A String in JavaScript

Reversing a string: a complete tutorial.

James Kerrane
James Kerrane
2 min readJul 10, 2017

--

Image from Javarevisited

Let’s say you had this string in JavaScript: “Howdy”. How do you reverse this string, then return it to the console?

First, let’s create a function called “reverseString”.

This function will take an input (str), and output the reversed string. To start, let’s create an array. This array will let us edit an instance of the string, and it will make it easier to reverse the string.

Now that we have the array, let’s separate our string into letters, and put our string into the array. To do this, we can use the .split object. This object takes another object (such as our array), and splits it into sub-arrays at each split point. To define a split point, we put what we want to split into parentheses.

Let’s break this down:

“array =” is defining array as “str.split(“”);”.

“str.split” is taking our string, and splitting it.

“.split(“”)” is looking through the code, and splitting the str into the array every letter. For example: “and” would turn into [“a”, “n”, “d”].

Now that we split the string into an array consisting of every letter, we now need to reverse the array.

Let’s break this down:

“array.reverse();” is reversing our array. For example: [“a”, “n”, “d”] would turn into [“d”, “n”, “a”].

Now that we have a reversed array, we need to turn this back into a string.

To do this, we can use the .join object.

Let’s break this down:

“str =” is defining our string as “array.join(‘’)”.

“array.join” is combining our array with our string.

“.join(‘’)” is telling .join to combine without creating commas.

Finishing Up:

Now that we have our reversed string, all we need to do is return it:

Calling the function:

To use our function that we just used, use this syntax:

Hope this helps!

If you liked this article, please 👏 below, so that other people can find it! :D

--

--