Reverse a String in JavaScript
📅March 30, 2022
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
- How to sort an array of objects in a specific order in JavaScript
- Automatically refresh or reload a page using JavaScript
- Get the YouTube video ID from a URL using JavaScript
- Remove the leading zero from a number in JavaScript
- Get query string parameters from URL in JavaScript
Methods to reverse a string in JavaScript
1. Using reverse function
Here we will use the chaining the three different methods together.
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.
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.
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..!! 🙂