Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string split
reverse string
join()
reverse()
communitycreator

Reversing a string using JavaScript

Sado Erick

Today, I came across a challenge that required me to reverse a certain string. I had done something of this nature a few days back, but surprisingly, I had to google how to reverse a string all over again. So, in order to remember the steps, I came up with my own formula:

.s.r.j("")

where:

  • .s stands for .split()
  • .r stands for .reverse()
  • .j stands for .join()

Say you are given a string to reverse e.g "hello". Let’s reverse it using our formula.

Split

The first step is to split the word:

var word = "hello";

var splitWord = word.split("");

Now, splitWord holds the following array:

['h', 'e', 'l', 'l', 'o']

The split() method splits the word into an array of standalone characters.

The empty string argument given to the method indicates that each character should be split up.

Reverse

The second step is to reverse the split word:

var reverseWord = splitWord.reverse();

This would output:

['o', 'l', 'l', 'e', 'h']

Join

Lastly, we will join the array of reversed letters

joinedWords = reverseWord.join("")

This would result in the final reversed string:

olleh

There you go! You have just reversed a word.

svg viewer

We could write all these methods in a single line as well:

var word = "Philosophy";
var reverseWord = word.split("").reverse().join("");
console.log("Reversed str is:", reverseWord);

So, next time you meet the reverse string challenge, just use the .s.r.j("") formula.

Using another string

Interestingly, I discovered that there is an alternate way to reverse a string (in case you have a hard time remembering the formula discussed above).

All we have to do is iterate the string in reverse and append each character to a new empty string. Let’s have a look at the code:

let word = "hello";
let reverseWord = "";

for (let i = word.length - 1; i >= 0; i--){
  reverseWord += word[i]
}

console.log("Reversed str is:", reverseWord);

Each character above is picked from the end of the given string; o from "hello" is picked first and appended to the empty string reversedWord. Once the loop ends, we have the full string in reverse!

RELATED TAGS

string split
reverse string
join()
reverse()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring