How do I reverse a string in JavaScript?
Alex K
alex k profile pic

In JavaScript, there are multiple ways to reverse a string. Let's explore some common approaches: 1. Using the split(), reverse(), and join() methods: This method involves splitting the string into an array of characters, reversing the array, and then joining the characters back into a string. Here's an example:

1
2
3
4
5

   var str = 'Hello, World!';
   var reversedStr = str.split('').reverse().join('');
   console.log(reversedStr); // Output: '!dlroW ,olleH'
   

In this code snippet, thesplit('') method splits the string into an array of characters. Thereverse() method reverses the order of the elements in the array, andjoin('') concatenates the elements of the array back into a string. 2. Using a for loop: Another approach is to use a for loop to iterate over the characters of the string in reverse order and build a new string. Here's an example:

1
2
3
4
5
6
7
8

   var str = 'Hello, World!';
   var reversedStr = '';
   for (var i = str.length - 1; i >= 0; i--) {
     reversedStr += str.charAt(i);
   }
   console.log(reversedStr); // Output: '!dlroW ,olleH'
   

In this example, we start the loop from the last character of the string (str.length - 1) and decrement the index until we reach the first character (i >= 0). We use thecharAt() method to access each character at the current index and append it to thereversedStr variable. 3. Using the spread operator and Array.from(): ES6 introduced the spread operator (...) and theArray.from() method, which can be used to convert a string into an array. We can utilize these features to reverse a string. Here's an example:

1
2
3
4
5

   var str = 'Hello, World!';
   var reversedStr = [...str].reverse().join('');
   console.log(reversedStr); // Output: '!dlroW ,olleH'
   

In this code snippet, the spread operator ([...str]) is used to convert the string into an array of characters. We then apply thereverse() method to reverse the array and usejoin('') to convert it back to a string. These are a few common approaches to reverse a string in JavaScript. Choose the method that best suits your coding style and requirements. Remember that strings in JavaScript are immutable, so the above methods create a new reversed string rather than modifying the original string.