In this article we will learn how to reverse a string.
Unfortunately, there is no built-in function in JavaScript that directly reverses a string, and this is where your role as a programmer comes in.
And if you are familiar with the basics of JavaScript, you will do so easily.
Problem
Well, now we have a problem, which is that we want to reverse the string.
This is our string:
Hello world
And we want to reverse it so that it becomes like this:
dlrow olleH
And we said that there's no built-in function that does this, so how will you solve this problem?
Think a little and then come back to the solution.
Solution:
Well, the solution is simple, there is not really a function that reverse the string, but there is a function that reverse the array, right?
Now the solution is to convert the string into an array, then reverse it, and then return it again as a string.
Summarize the solution as follows:
- Convert string into an array
- Reverse the string
- Convert back the array to a string
I know, I know, it might be a little difficult for you, especially if you are a beginner.
But after writing the code things will start to make sense.
// Our string
const myString = "Hello world";
// Convert string to an array
const toArray = myString.split("");
// Reverse array
const reversedArray = toArray.reverse();
// Return it back to string
const result = reversedArray.join("");
// Print result
console.log(result);
Output
dlrow olleH
Ok, do you understand the previous code? We consider the answer is no.
Explanation of the solution:
First of all, we convert the string into an array with the split function.
// Convert string to an array
const toArray = myString.split("");
console.log(toArray);
Output
[
'H', 'e', 'l', 'l',
'o', ' ', 'w', 'o',
'r', 'l', 'd'
]
Well now that the string is an array, what next?
There is a built-in function that reverse the array, right? We will use it.
// Reverse array
const reversedArray = toArray.reverse();
console.log(reversedArray);
Output
[
'd', 'l', 'r', 'o',
'w', ' ', 'o', 'l',
'l', 'e', 'H'
]
Now we will return that array to a string using join method
// Return it back to string
const result = reversedArray.join("");
console.log(result);
Output
dlrow olleH
Yay! ๐ And here the solution is complete, if you have another solution let me know :)
Thank you for reading
Thank you for reading my blog. ๐ You can find more awesome article in my blog ๐