
If you’re a JavaScript developer, you will likely come across situations where you need to reverse a string. In this blog post, we will explore various methods to do this, from the traditional approach of using built-in methods to the more complex techniques of using a loop. So, let’s get started and unravel the mystery of reversing strings in JavaScript!
How to reverse a string in JavaScript?
There is no native method built into String
prototype, so to do this we need to use methods that we used trying to reverse an array in JavaScript. Long story short, we need to convert a string to an array of letters, reverse it, and convert them back to a string.
let message = "Hello world!";
message.split('').reverse().join('');
Above code works very well if you are trying to reverse ASCII string. If you need a solution that supports Unicode characters (or other multi-byte characters), you have to little modify this solution and use string destructuring instead of split
method.
let message = "This string contains multi-byte emoji 😎";
[...message].reverse().join('');
In the above example, we just changed message.split('')
to […message]
. Generally, both are doing the same, but the second one is using destructuring assignment to convert string to an array, and it supports multi-byte characters.
Finally, you can use Array.from
method to convert string into an array. This method also supports multi-byte characters.
Array.from("Other string with emoji 😎").reverse().join('');
How to reverse a string in JavaScript with the loop?
If for some reason you want to reverse a string in JavaScript without using the above methods, you can always create a for
loop to do this in a more complex way. To achieve this, we need to go through the loop as many times as string length. For each iteration we ned to pick one of the letters and add it to a separate variable. Of course, we need to picks the letters from the end to the beginning of this string:
let message = "Hello, my friend!";
let reversedMessage = "";
for (let i = message.length - 1; i >= 0; i--) {
reversedMessage += message.charAt(i)
}
It is worth noticing that we have a lot of methods and ways to pick a specific letter from a string. We covered almost all of these when we learning how to get first character of a string in JavaScipt.
Now you are able to reverse a string in JavaScript, both by using simple built-in methods and by using for
loop.
Leave a Reply