Reversing A String Using JavaScript
Maybe your like
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:
ollehThere you go! You have just reversed a word.
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);RunSo, 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);RunEach 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!
Relevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Tag » How To Reverse A String Javascript
-
Three Ways To Reverse A String In JavaScript - FreeCodeCamp
-
How Do You Reverse A String In-place In JavaScript? - Stack Overflow
-
JavaScript Program To Reverse A String - Programiz
-
Reverse A String In JavaScript - GeeksforGeeks
-
How To Reverse A String In JavaScript
-
How To Reverse A String In JavaScript - Stack Abuse
-
Three Ways To Reverse A String In JavaScript - Medium
-
Methods To Reverse String In JavaScript - Flexiple
-
How Do You Reverse A String In Place In JavaScript? - Tutorialspoint
-
verse() - JavaScript - MDN Web Docs
-
How Do I Reverse A String In JavaScript? - ReqBin
-
How To Reverse A String In Python - W3Schools
-
Reverse A String In JavaScript - DEV Community
-
How To Reverse A String In JavaScript - Mastering JS