Author -  Sai gowtham

JavaScript - How to Reverse a String (3 ways)

In this tutorial, we are going to learn three different ways to reverse a string in JavaScript by using the reverse() method, reduce() method, while loop.

Reversing the string

To reverse a string in JavaScript, we can use the combination of split(), reverse() and join('')methods.

Here is an example:

const str = "hello"
const reverse = str.split('').reverse().join('');

console.log(reverse); // "olleh"

In the above example, we used the split() method to split the given string into an array of individual characters then chain it to reverse(), join() methods.

split(): The split() splits the given string into an array of individual characters.

reverse(): The reverse() method reverses the array.

join(): The join() method joins the array of individual characters into a string.

Using reduce() method

To reverse a string , we can use the reduce() method in JavaScript.

const str = "hello"
const reverse = [...str].reduce((prev,next) => next+prev);

console.log(reverse); // "olleh"

In the example above, first we unpack the string into a array of individual characters using spread operator (…) then we reverses the string using the reduce() method.

Using while loop

function reverseString(str){

  const arr = [...str];
  let reverse= "";

  while(arr.length){
    // joining the reversed string
     reverse = reverse + arr.pop();
  }

  return reverse;
}

console.log(reverseString('hi')); // ih

I mostly like the Second way to reverse a string using reduce() method.

Happy coding…

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY