Reverse a String in JavaScript
In the technical round of the interview, reversing a string is one of the most often asked JavaScript questions. Interviewers may ask you to write different ways to reverse a string, or to reverse a string without using built-in methods, or to reverse a string using recursion. We are making a list of three methods that we prefer.
Checkout more articles on JavaScript
Methods to reverse a string in JavaScript
1. Using reverse function
Here we will use the chaining the three different methods together.
1 2 3 4 5 | function reverse(str) { return str.split('').reverse().join(''); } reverse('Clue Mediator'); // Output: rotaideM eulC |
2. Looping through characters
Let’s use the for
loop to reverse the string.
1 2 3 4 5 6 7 8 9 10 11 | function reverse(str) { let reversed = ''; for (let character of str) { reversed = character + reversed; } return reversed; } reverse('Clue Mediator'); // Output: rotaideM eulC |
3. Using reduce function
In the last method, we will use the reduce method to get the output.
1 2 3 4 5 | function reverse(str) { return str.split('').reduce((rev, char) => char + rev, ''); } reverse('Clue Mediator'); // Output: rotaideM eulC |
Here, we have mostly used Arrays methods. You can check the following article to know more about it.
Use of Array methods
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂