I recently started studying data structures and algorithms, and one of the first challenges that came up was reversing a string. Reversing a string is a very common challenge that comes up in Javascript interviews. The interviewer may ask you to solve this challenge in different ways.
Here are 3 ways you can reverse a string in Javascript:
1. Use Javascript built-in methods
In this method, we will use 3 built-in methods in Javascript: String.prototype.split(), Array.prototype.reverse(), and Array.prototype.join().
- The
.split()
method splits a String object into a new array of substrings. - The
reverse()
method mutates an Array object and reverses it. The last element in the array will become the first, and the first element will become the last. - The
join()
method takes an Array object and joins the elements together into a new string.
function reverseString(str) {
// Step 1. Use the split() method to return a new array
let splitString = str.split(""); // "hello".split("");
// ["h", "e", "l", "l", "o"]
// Step 2. Use the reverse() method to reverse the newly created array
let reverseArray = splitString.reverse(); // ["h", "e", "l", "l", "o"].reverse();
// ["o", "l", "l", "e", "h"]
// Step 3. Use the join() method to join all elements of the array into a string
let joinArray = reverseArray.join(""); // ["o", "l", "l", "e", "h"].join("");
// "olleh"
//Step 4. Return the reversed string
return joinArray; // "olleh"
}
reverseString("hello");
The reverseString
function above can be rewritten by chaining all three methods:
function reverseString(str) = {
return str.split("").reverse().join("") // "olleh"
}
reverseString("hello");
2. Use a reverse (decrementing) for loop
function reverseString(str) {
// Step 1. Create an empty string that will house the new reversed string
let newString = "";
// Step 2. Create the FOR loop
/* The starting point of the loop will be (str.length - 1) which corresponds to the
last character of the string, "o"
As long as i is greater than or equals 0, the loop will continue
We decrement i after each iteration
Once i is less than 0, the loop stops */
for (let i = str.length - 1; i >= 0; i--) {
newString += str[i]; // add the character into the new string
}
/* Here hello's length equals 5
For each iteration: i = str.length - 1 and newString = newString + str[i]
First iteration: i = 5 - 1 = 4, newString = "" + "o" = "o"
Second iteration: i = 4 - 1 = 3, newString = "o" + "l" = "ol"
Third iteration: i = 3 - 1 = 2, newString = "ol" + "l" = "oll"
Fourth iteration: i = 2 - 1 = 1, newString = "oll" + "e" = "olle"
Fifth iteration: i = 1 - 1 = 0, newString = "olle" + "h" = "olleh"
End of the FOR loop*/
// Step 3. Return the reversed string
return newString; // "olleh"
}
reverseString("hello");
3. Use recursion
For this method, we will be using the String.prototype.substr() method:
- The
.substr()
method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.
"hello".substr(1); // "ello"
A recursive function is simply a function that calls itself. It consists of a base case and a recursive call where the base case stops the function and the recursive call is where the function calls itself. Without a base case, the function would continue in an infinite loop.
function reverseString(str) {
if (str === "") { // This is the base case that will end the recursion
return "";
} else {
return reverseString(str.substr(1)) + str[0]; // This is the recursive call
}
}
/*
First Part of the recursive function:
You will have several nested calls to reverseString(), each time passing in a substring of the previous string
Each call: str === "?" will return reverseString(str.substr(1)) + str[0]
1st call: reverseString("hello") will return reverseString("ello") + "h"
2nd call: reverseString("ello") will return reverseString("llo") + "e"
3rd call: reverseString("llo") will return reverseString("lo") + "l"
4th call: reverseString("lo") will return reverseString("o") + "l"
5th call: reverseString("o") will return reverseString("") + "o"
Second part of the recursive function:
The function hits the base case and the most highly nested call returns immediately (the 5th call returns first)
5th call will return reverseString("") + "o" = "o"
4th call will return reverseString("o") + "l" = "o" + "l"
3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"
2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"
1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h"
*/
}
reverseString("hello");
Top comments (1)