JavaScript – Reverse a String

In this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse().

Using the built-in reverse method

The reverse() method is typically used on arrays, so we first need to convert the string to an array.

function reverseString(str) {
    return str.split('').reverse().join('');
}

// Example usage:
const originalString = "Hello, World!";
const reversedString = reverseString(originalString);
console.log(reversedString); // Output: "!dlroW ,olleH"

Using a for-loop

In this approach, we reverse the string by iterating over the string from the end to the beginning.

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

console.log(reverseStringWithForLoop('Hello')); // Output: "olleH"

Using spread + reverse

The spread operator splits the string into an array of characters, which we then reverse and join back into a string.

function reverseStringWithSpreadOperator(str) {
  return [...str].reverse().join('');
}

console.log(reverseStringWithSpreadOperator('Hello')); // Output: "olleH"

Similar Reads