Reverse a string in JavaScript
In this post, we will learn how to reverse a string in JavaScript using different methods and techniques.
Reversing a string means creating a new string that contains the same characters as the original string, but in the opposite order. For example, reversing the string “reverse” would result in “esrever”. Since strings are immutable in JavaScript, in-place string reversal is not possible. There are several ways to create a reversed copy of the string with JavaScript:
1. Using Built-in Methods
The simplest and most straightforward way to reverse a string in JavaScript is to use the built-in methods of the String and Array objects. These methods are:
- The
String.prototype.split('')orArray.from()or ES6 spread syntax (…), which splits a string into an array of substrings. - The
Array.prototype.reverse()method, which reverses the order of the elements in an array. - The
Array.prototype.join()method, which joins all the elements of an array into a string using a separator.
By chaining these methods together, we can easily reverse a string in one line of code:
|
1 2 3 4 5 6 7 8 9 10 |
function reverseString(str) { const reverse = str.split('') // or use `Array.from(str)` or `[…str]` .reverse() .join(''); return reverse; } const str = 'reverse'; console.log(reverseString(str)); // esrever |
This method is concise and easy to understand, but it creates an intermediate array, which consumes extra memory and time. Alternatively, we can use the Array.prototype.reduce() method for reversing a string, as demonstrated below:
|
1 2 3 4 5 6 |
function reverseString(str) { return str.split('').reduce((x, y) => y + x); } const str = 'reverse'; console.log(reverseString(str)); // esrever |
Both these methods will not work well with Unicode characters that are composed of multiple code units, such as emojis or accented letters. For example:
|
1 2 3 4 5 6 |
function reverseString(str) { return str.split('').reverse().join(''); } console.log(reverseString("????")); // "∩┐╜∩┐╜" console.log(reverseString("é")); // "├⌐" |
As we can see, the reversed strings are not valid Unicode characters. This can cause unexpected results or errors when working with Unicode strings.
2. Using third-party libraries
The Underscore.string extension offers several utility functions for string manipulation. It has the _.reverse method for reversing a string.
|
1 2 3 4 5 |
const _ = require('underscore.string'); const str = 'reverse'; const reverse = _.reverse(str); console.log(reverse); // esrever |
However, it still does not handle Unicode characters properly, as it treats each code unit as a separate character. Lodash.js has the _.reverse method to reverse an array. We can use it similarly by constructing an array from the string, reverse it, then join it back to a string.
|
1 2 3 4 5 6 |
const _ = require('lodash'); const str = 'reverse'; const reverse = _.reverse(str.split('')).join(''); console.log(reverse); // esrever |
3. Using a Loop
Another way to reverse a string in JavaScript is to use a loop to iterate over the characters of the string and append them to a new string in reverse order. There are different ways to implement this method, such as using a for loop, a while loop, or a for…of loop. Here is an example using a for loop:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function reverseString(str) { // Create an empty string that will host the new reversed string let reversed = ''; // Loop over the original string from the end to the beginning for (let i = str.length - 1; i >= 0; i--) { // Append each character to the reversed string reversed += str[i]; } // Return the reversed string return reversed; } const str = 'reverse'; console.log(reverseString(str)); // esrever |
Another option to do this is to use the spread operator (…), which spreads the elements of an iterable object (such as a string) into individual arguments. Here is an example using the for…of loop:
|
1 2 3 4 5 6 7 8 9 10 11 |
function reverseString(str) { let reversed = ''; for (let char of [...str]) { reversed = char + reversed; } return reversed; } const str = 'reverse'; console.log(reverseString(str)); // esrever |
This method does not create an intermediate array, so it is more efficient in terms of memory and time. However, it still does not handle Unicode characters properly.
4. Using Recursion
Recursion is a technique where a function calls itself until a base case is reached. Recursion can be used to reverse a string in JavaScript by taking the first character of the string and appending it to the reversed version of the rest of the string. Here is how we can implement this method in JavaScript:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function reverseString(str) { // If the string is empty, return it as the base case if (str === '') { return str; } // Otherwise, take the first character and append it to the // reversed version of the rest of the string return reverseString(str.slice(1)) + str[0]; } const str = 'reverse'; console.log(reverseString(str)); // esrever |
This method is elegant and concise, but it has some drawbacks. First, it creates a lot of intermediate strings, which consumes extra memory and time. Second, it does not work well with long strings, as it can cause a stack overflow error due to too many recursive calls. Third, it does not handle Unicode characters properly, as it treats each code unit as a separate character.
That’s all about reversing a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)