In this article we will learn how to reverse a string.
Well, now we have a problem, which is that we want to reverse the string.
This is our string:
And we want to reverse it so that it becomes like this:
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.
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);
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);
[ '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);
[ '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);
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.