String reversal is probably the most common algorithm question ever in the history of programming. In how many ways can you reverse a given string?
stringReversal("samson"); //nosmas
stringReversal("njoku samson ebere"); //erebe nosmas ukojn
We will be looking at seven (7) ways we can reverse a given string in this article.
Prerequisite
To flow with this article, it is expected that you have basic understanding of javascript's string methods and/or array methods.
Reversing a string using:
- Only javascript built-in methods
function stringReversal(str) {
let newString = str
.split("")
.reverse()
.join("");
return newString;
}
- Javascript built-in methods and spread operator
function stringReversal(str) {
let newString = [...str].reverse().join("");
return newString;
}
- for...loop
function stringReversal(str) {
let newString = "";
for (let i = str.length; i >= 0 ; i--) {
newString += str[i];
}
return newString;
}
- for...in loop
function stringReversal(str) {
let newString = "";
for (s in str) {
newString = str[s] + newString;
}
return newString;
}
- for...of loop
function stringReversal(str) {
let newString = "";
for (s of str) {
newString = s + newString;
}
return newString;
}
- reduce() and spread operator
function stringReversal(str) {
let newString = [...str].reduce((acc, char) => char + acc);
return newString;
}
- reduce() and split() method
function stringReversal(str) {
let newString = str.split("").reduce((acc, char) => char + acc);
return newString;
}
Conclusion
There are many ways to solve problems programmatically. You are only limited by your imagination.
Aside these seven, there are others ways to solve the string reversal problem too. Feel free to let me know other ways you solved yours in the comment section.
If you have questions, comments or suggestions, please drop them in the comment section.
Up Next: Algorithm 101: 13 Ways to Count Vowels in a String
You can also follow and message me on social media platforms.
Thank You For Your Time.
Top comments (3)
Thanks for elaborately showing these methods...
I now know other methods of solving string reversal problems. I have observed that the last example is missing the .reverse array method, thus will return the original string as the result.
First time I did this challenge without hint. I made an empty array, looped through each character in my string and used unshift. That was a bad code I know
🤣 🤣 🤣 🤣 🤣
We keep growing daily