JavaScript – Reverse a String

To reverse a given string in JavaScript

  1. Split the string into an array of characters using String.split() method.
  2. Reverse the array of characters using Array.reverse() method.
  3. Join the array of characters Array.join() method.

The expression that returns a reversed string for a given string str is

</>
Copy
str.split("").reverse().join("")

Example

In the following example, we take a string str, reverse the string, and display the original and reversed string in pre#output.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var str = 'apple';
        var reversedStr = str.split("").reverse().join("");

        var output = 'Original string  : ' + str;
        output += '\n\nReversed string  : ' + reversedStr;
        document.getElementById('output').innerHTML = output;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to reverse a given string in JavaScript, with example program.