Home » Programming » Javascript » Javascript Reverse String

How to Reverse a String in JavaScript in One Line of Code [Example]

This quick tutorial will show you how to reverse a string in JavaScript.

Strings are Array-Like

Strings in JavaScript are considered array-like. A string is an ordered series of characters, so it can be considered as an array of characters.

This makes it easy to convert a string to an array. We can then use any one of the methods available for reversing the array to reverse the string.

This means you can use any of the methods we’ve previously outlined on reversing arrays on strings.

Reversing a String in JavaScript with a Single Line of Code

The simplest way to reverse a string is to convert the string to an array of characters, and then call the array reverse() method.

Once reversed, the string can be re-assembled.

var myString = "abcdefg";
var myReversedString = myString.split("").reverse().join("");
console.log(myString);
console.log(myReversedString);

Above, a variable myString containing a string is defined.

A second variable to hold the reversed string myReversedString is then defined with a value constructed by converting the string to an array of characters using the split() method, which is then reversed with the reverse() method, and finally re-assembled in the reversed order using the join() method.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment