Sling Academy
Home/JavaScript/3 Ways to Reverse a String in JavaScript

3 Ways to Reverse a String in JavaScript

Last updated: February 27, 2023

Reversing a string means changing its order so that the last character becomes the first, and the second last character becomes the second, and so on. This straightforward, example-based article shows you a couple of different ways to reverse a given string in JavaScript.

Using the split(), reverse(), and join() methods

Example:

const reverseString = (str) => {
  return str.split('').reverse().join('');
};

console.log(reverseString('ABCDEF'));
console.log(reverseString('123456'));

Output:

FEDCBA
654321

Using a loop

Example:

const reverseString = (str) => {
  let reversed = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
};

console.log(reverseString('Welcome to Sling Academy!'));

Output:

!ymedacA gnilS ot emocleW

Using the spread operator

This approach is quite similar to the first approach, but instead of using the split() method, we use the spread operator.

Example:

const str = "This is a secret message!";
const reversed = [...str].reverse().join("");
console.log(reversed);

Output:

!egassem terces a si sihT

Next Article: 4 Ways to Extract a Substring from a String in JavaScript

Previous Article: JavaScript: Convert a String to Upper or Lower Case

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration