How to Reverse a String in JavaScript
Reversing a string in JavaScript with split, reverse and join.
Reversing a string is one of those small problems that shows up in coding
interviews all the time. Strings don't have a reverse method, but arrays do,
so the trick is to turn the string into an array first.
Using split, reverse and join
This is the classic one liner:
const reverse = (str) => str.split("").reverse().join("")reverse("hello") // "olleh"
Here's what each step does:
split("")turns the string into an array of characters:["h", "e", "l", "l", "o"]reverse()reverses the array in place:["o", "l", "l", "e", "h"]join("")glues the characters back into a string:"olleh"
Using the Spread Operator
split("") splits a string into UTF-16 code units, not characters. That's fine
for plain text, but emoji and some other characters are made of two code units,
and splitting them breaks them apart:
"hi 👋".split("").reverse().join("") // "�� ih"
The spread operator splits a string by characters instead, so it keeps them in one piece:
const reverse = (str) => [...str].reverse().join("")reverse("hi 👋") // "👋 ih"
This is the version I'd reach for.
Using a for Loop
In an interview you may be asked to do it without the built in methods. A loop that starts from the end works fine:
function reverse(str) {let reversed = ""for (let i = str.length - 1; i >= 0; i--) {reversed += str[i]}return reversed}reverse("hello") // "olleh"
Have some feedback on this post? .