Skip to content

Edvins Antonovs

How to reverse a string in JavaScript

Reversing a string is one of the common programming challenges you can come across. The idea of this challenge is to transform the given string and return a new string with reversed order of character. There are different techniques how you can approach implementing it like built-in JavaScript methods, for loop or even using a reduce function.

What we trying to achieve:

1console.log(reverse('reverse'));
2// Output: "esrever"
3
4console.log(reverse('Hello World!'));
5// Output: "!dlroW olleH"

1. Using split(), reverse(), and join()

This is a self-explanatory method where we use a sequence of built-in JavaScript methods together.

First of all, we split() the string into an array of substrings using a separator "" to return a new array. Secondly, we use reverse() method to reverse the order of all elements in an array. Meaning that the first element becomes the last, and the last, and the last becomes the first. Finally, we use join() method to join all elements of the array into a new string.

1function reverse(str) {
2 return str.split('').reverse().join('');
3}
4
5console.log(reverse('edvins'));
6// Output: "snivde"

2. Using for loop

In this example, we are iterating through all characters in the string to return the reversed string as a result.

1function reverse(str) {
2 let result = '';
3
4 for (let char of str) {
5 result = char + result;
6 }
7
8 return result;
9}
10
11console.log(reverse('edvins'));
12// Output: "snivde"

3. Using reduce()

The reduce() method is used to execute a function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

In our case, we start by splitting our string using split(), then we use reducer() to execute (rev, char) => char + rev function, where rev represents a previous value, while char — the current one. Additionally, we pass "" as a second parameter, it's out initial state.

1function reverse(str) {
2 return str.split('').reduce((rev, char) => char + rev, '');
3}
4
5console.log(reverse('edvins'));
6// Output: "snivde"

Appendix

© 2024 by Edvins Antonovs. All rights reserved.