Sitemap

JavaScript — Reverse a String — Codeymaze

1 min readSep 10, 2024

--

Press enter or click to view image in full size

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('');
}

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

Get CodeyMaze’s stories in your inbox

Join Medium for free to get updates from this writer.

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"

Originally published at https://codeymaze.com on September 10, 2024.

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)