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.