06 Aug, 2023
Hey, Fuelers!
Have you ever needed to reverse a string in JavaScript and not known where to start?
Don't worry, In this quick tutorial, I'm going to show you how to reverse a string in JavaScript in just a few lines of code.
Let's Dive in!
There are a few use cases why you might need to reverse a string:
In this section, I will share how you can use for loop to reverse a string in js.
Loop through the string character by character. Start at the last character and work your way to the first. For each character, concatenate it to the beginning of an empty string.
For example, say you want to reverse the string "hello". You'd do:
let reversed = '';
for (let i = 'hello'.length - 1; i >= 0; i--) {
reversed += 'hello'[i];
}
console.log(reversed); // Output: "olleh"
This loops through each character in "hello" starting at index 4 and going down to 0. For each character, it's concatenated to the beginning of the reversed string. So in the first iteration, 'o' is concatenated, then 'l', and so on until you have "olleh".
See? Reversing a string in JavaScript is pretty straightforward.
.Split()
.reverse()
.join()
To reverse a string in JavaScript, you have a few options. The easiest way is to use the .split()
, .reverse()
and .join()
methods.
.split()
.reverse()
.join()
This works by:
.split()
.reverse()
.join()
For example:
let str = "Hello";
let reversed = str.split("").reverse().join("");
console.log(reversed); // olleH
This will print "olleH" - the reversed version of the string "Hello".
You can also split on words or any character you want by passing a delimiter to .split(). For example, to reverse the sentence "Hello world!":
let str = "Hello world!";
let reversed = str.split(" ").reverse().join(" ");
console.log(reversed); // world! Hello
This technique works for reversing any string in JavaScript. It's a simple yet effective way to flip a string using built-in methods.
Give this a try yourself! Open up your browser's JavaScript console and enter some strings to reverse. See how the .split()
, .reverse()
and .join()
methods work in action.
Let's see how to reverse a string recursively, Recursion is mind-boggling but this simple tutorial is not.
Recursion is when a function calls itself. It's a mind-bending concept at first but stick with me.
To reverse a string recursively, you need a base case.
The base case is the condition that will stop the recursion. For string reversal, the base case is a string with 0 or 1 characters. Otherwise, you call the function again with a smaller part of the string.
Here's the code:
function reverseString(str) {
if (str.length <= 1) {
return str;
}
return str[str.length - 1] + reverseString(str.slice(0, str.length - 1));
}
Let's walk through this. The base case checks if the string is empty or has 1 character. If so, just return the string.
Otherwise, we take the last character of the string using str[str.length - 1]
and concatenate (add) it with the reversed portion of the rest of the string. We get the rest of the string by slicing from index 0 up to but not including the last character.
Then we call reverseString again, passing in the rest of the string. This continues until we hit the base case, and the calls unwind, giving us the fully reversed string.
Confused? Let's look at an example. If we call reverseString("hello")
, here's what happens:
reverseString("hello")
"o" + reverseString("hell")
// Take last char and recurse"l" + reverseString("hel")
// Take last char and recurse"l" + "e" + reverseString("h")
"h" + "e" + "l" + "l" + "o"
// Base case hit, unwind callsThe final result is "olleh"
. And Done.
So you’ve learned how to reverse a string in JavaScript, but you probably still have some questions.
Reversing strings is a common programming task that comes up in both technical interviews and real-world coding. It demonstrates your ability to manipulate strings, a fundamental data type in any language.
Reversing a string also has some practical uses, like reversing a word to check if it’s a palindrome.
A few things to keep in mind when reversing strings:
So there you have it, a quick and simple way to reverse a string in JavaScript. Programming is all about building up these little skills that you can combine in interesting ways.
Keep practicing and building fun little projects to strengthen your JavaScript skills.
Happy Coding!
Trusted by 49900+ Generalists. Try it now, free to use
Start making more money