How to Reverse a String in JavaScript

How to Reverse a String in JavaScript

Introduction

Reversing a string isn't uncommon in development, and fairly popular for entry-level interview questions. With JavaScript, we have many ways to reverse a string. We can use a combination of string's split() method as well as array's reverse() and join() methods (since strings are ultimately arrays of characters).

We can also reverse a string with our own iterative (loop) or recursive functions.

In this guide, we'll take a look at several ways to reverse a string in JavaScript.

Using Built-in Methods to Reverse the String - split(), reverse() and join()

The simplest way to reverse a string in JavaScript is to split a string into an array, reverse() it and join() it back into a string. With ES6, this can be shortened and simplified down to:

let string = "!onaiP"
string = [...string].reverse().join("");

console.log(string); // "Piano!"

Here, the Spread Syntax is used to split the string into an array and is functionally equivalent to the split() method, which you could also use instead.

To understand why they all work together, let's overview what each function does.

split()

The split() method returns a new array of strings after splitting a string with the provided separator:

string.split(separator, limit)

The separator defines where the string splits into an element in the resulting array. We can define the number of the array element with the limit parameter. When we use the split() method with an empty string, '', the string will be split on every character. It will come in handy when we convert our string into an array of individual characters.

Again, you can use the spread operator to achieve the same result. The spread operator is a JavaScript operator that works on the iterables like an array, string, and objects. We can copy and concatenate objects and arrays using the spread operator:

[...myVar, 4, 5, 6] // combines myVar array with the given elements
myFunc(...myVar) // Use the myVar's elements as argument to the function

When the spread operator is used with a string, the string is converted into a sequence of characters:

let str = 'hello';
console.log([...str]); // ["h","e","l","l","o"]
console.log(str.split('')); // ["h","e","l","l","o"]

Note: While splitting UTF-16 characters, use the spread operator instead of the split() method.

reverse()

The reverse() returns a reversed array, in-place. That's to say - the original array is reversed instead of a copy that's returned as the result:

let str = ['a','b','c','d'];
let reversedStr = str.reverse();
console.log(str); // ["d","c","b","a"]
console.log(reversedStr); // ["d","c","b","a"]

You don't need to assign the result to a new variable, though, we commonly do in order to change the variable name to a more indicative one.

join()

The join() method concatenates the elements of an array and returns a string. We can also specify a separator, which is optional, to join the elements. When we use the default separator, the elements will be separated by a comma in the string. Using an empty string as the separator will concatenate the array elements and return as a string as usual:

let str = ['a','b','c','d'];
console.log(str.join('')); // "abcd"
console.log(str.join()); //  "a,b,c,d"
console.log(str.join(' - ')); // "a - b - c - d"

Combining the Built-in Methods to Reverse the String

With all of that in mind - the way these work together becomes intuitive:

let str = 'guitar';
console.log('The original string is: ' + str);
let splitStr = str.split(''); // ["g","u","i","t","a","r"]
let reversedArr = splitStr.reverse();
let reversedStr = reversedArr.join('');
console.log("The reversed string is: " + reversedStr);

Or, you can shorten it down to:

let reversedStr = [...str].reverse().join('');
// Or
let reversedStr = str.split('').reverse().join('');

The code above results in:

The original string is: guitar
The reversed string is: ratiug

Using a for Loop to Reverse the String

With a for loop, we can iterate over each character from the string. Starting from the end of the string to the beginning of the string - we can continuously append the characters to a new string and thus form a reversed string:

const str = 'guitar';
console.log('The original string is: ' + str);
let reversedStr = '';

for (let i = str.length - 1; i >= 0; i--) {
  reversedStr += str[i];
}

console.log('The reversed string is: ' + reversedStr);

Here, we created an empty string, reversedStr, to hold the reversed string. String indices are like array indices, they start at 0. Therefore, we started the loop from one less than the length of the string (picking up the letter r) and loop till our counter goes to 0 (with the letter g).

The reversedStr variable concatenates the elements of the string.

Running the code gives us this output:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The original string is: guitar
The reversed string is: ratiug

Using Recursion to Reverse the String

Recursion is a process where a function calls itself. However, a function that calls itself may end up calling itself infinitely, and the process will never end without an exit condition. Therefore, we provide a condition, namely the base condition, to end the recursive behavior of the function.

We can use recursion to solve problems by writing very few lines of code without the hassle of iterating. However, this process can be slow if the recursion depth is high.

The syntax of a generic recursive function looks like this:

function recursion(){
    .......
    base condition
    recursion()
    .......
}

recursion()

When the recursion() function is called, it first checks some condition, and if evaluated to true - the function calls itself. This process is then repeated, again, and again. When the condition fails, the recursion is stopped, and the function returns a value.

We can use recursion to reverse a string in JavaScript using some string methods like substring() and charAt().

The substring() method extracts a part of the string. We can pass the start and end indices in the method as the parameters. If only the start index is supplied to the method - it will extract the string from that index until the last one.

But, when we supply both the start and the end index, it will extract the string from the start index but does not include the end index:

let str = 'hello'
console.log(str.substring(1)) //"ello"
console.log(str.substring(1,3)) //"el"

The charAt() method extracts the indexed character from a string. It returns a new string consisting of the character. An example of the method is shown below.

let str = 'hello'
console.log(str.charAt(2)) // "l"

For our recursive function - we first check whether the string is empty as the base condition. After a series of recursive calls, the string will become empty, and the recursion will end. Inside the reverse() function, the recursive reverse() function is given substring(1) as its parameter.

The charAt() method is concatenated with the reverse() function in the return statement:

function reverse(str) {
  if (str === '')
    return '';
  else
    return reverse(str.substring(1)) + str.charAt(0);
}

let str = 'guitar'
console.log('The original string is: ' + str);
const output = reverse(str);
console.log('The reversed string is: ' + output);

In the first recursive call, reverse("guitar") will result reverse("uitar") + "g". In the second call, reverse("uitar") will result reverse("itar") + "u". Likewise, the final recursive call, reverse("o") will return an reverse("")+ "r".

Now the execution of the else part is terminated, and the recursion will travel back its depth. At the final call, the string r is added to reverse(''), which results in the string r.

Next, the function call moves one step above where the string a is added to reverse("r"). It makes the string ra. Likewise, t is added with ra, and it becomes rat. Similarly, the recursion depth is traversed upwards, and it finally returns the string ratiug:

The original string is: guitar
The reversed string is: ratiug

Conclusion

In this article we discussed how to reverse a string. We used the built-in split(), reverse() and join() methods, the spread operator, created a for loops that creates a new reversed string, and a recursive function using substring() and charAt() which all produced the same results.

Last Updated: December 28th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Getting Started with AWS in Node.js

    Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

    © 2013-2022 Stack Abuse. All rights reserved.