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"
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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn 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… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays