How To Reverse a String (JavaScript)

How To Reverse a String (JavaScript)

I came across this task in a Palindrome Problem on LeetCode. In this article, I will explain how to reverse a string.

How To Reverse a String

const string = "abcdefg";
const reversed = string.split('').reverse().join('');
console.log(reversed)  //gfedcba

Step 1: Divide the String

The split() method will split the string in an array. If there are no separators specified in the method, it will return a copy of the whole string. Below is an example:

const string = "How are you?";
const copy = string.split()
const words = string.split(' ')
const characters = string.split('')

console.log(copy)  //(1) ["How are you?"]
console.log(words)  //(3) ["How", "are", "you?"]
console.log(characters)  //(12) ["H", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u", "?"]

So to divide the string into characters, use the split method with an empty string as a separator.

const string = "abcdefg";
const split = string.split('')
console.log(split)  //(7) ["a", "b", "c", "d", "e", "f", "g"]

Step 2: Reverse the String

The reverse() method reverses an array in place. I wrote a short article about it here.

const string = "abcdefg";
const reversed = string.split('').reverse()
console.log(reversed)  //(7) ["g", "f", "e", "d", "c", "b", "a"]

Step 3: Join the Array

Finally, merge the array with the join() method. Set a separator for the join() method. If the separator is omitted, the array elements are separated with a comma (","). For example:

const array = ["How", "are", "you", "?"];
const withComma = array.join()
const withoutComma = array.join('')
const withSpace = array.join(' ')

console.log(withComma)  //How,are,you,? 
console.log(withoutComma)  //Howareyou? 
console.log(withSpace)  //How are you ?

To convert the reversed array into a string, join the array as below.

const string = "abcdefg";
const reversed = string.split('').reverse().join('');
console.log(reversed)  //gfedcba

Summary

To reverse a string, use a combination of split, reverse, and join method on a string.

const string = "abcdefg";
const reversed = string.split('').reverse().join('');
console.log(reversed)  //gfedcba

Thank you for reading! I hope you enjoyed it!

Reference

MDN docs for String.prototype.split()

MDN docs for Array.prototype.reverse()

MDN docs for Array.prototype.join()

JavaScript Algorithms: Palindromes

How to reverse a number in JavaScript