How to reverse a string in Javascript in one line

How to reverse a string in Javascript in one line :

As we know, string is immutable, so if we need to reverse a string, we can’t just change the position of all characters. In this tutorial, we will learn how to reverse a string in Javascript. I will show you the exact steps required to reverse a string and how to do it in one line. Let’s take a look :

Reversing a string :

For example, if we reverse the hello string, it should be olleh. Since we cannot modify the characters of a string, we need to think a different way. Suppose our input is an array [‘h’,’e’,’l’,’l’,’o’], we can easily reverse it by calling .reverse() method. It will become [‘o’,’l’,’l’,’e’,’h’]. Great. That means we need to convert the string to an array of characters first. Thankfully, we can do this conversion using .split(“”) method. It will split the string to an array of its characters.

Now, we have one array with all characters of the string in reverse order. For converting this array to a string, we can use join(”) method.

Let’s try to write this in code :

var strArray;

function reverseString(inputStr) {
  // 1
  strArray = inputStr.split("");

  //2
  strArray.reverse();

  //3
  inputStr = strArray.join("");
  return inputStr;
}

console.log(reverseString("Hello"));
console.log(reverseString("Welcome"));
console.log(reverseString("Hello World"));

Explanation :

The commented numbers above denote the step numbers below :

1. Function reverseString takes one string as input, reverse it and returns it back. First of all, as explained above, split the string to an array and store it in strArray array variable.
2. Reverse this array.
3. join this array characters and store it in the string inputStr . Finally, return it back.

This program will print the below output :

olleH
emocleW
dlroW olleH

javascript reverse string

We can also convert the whole program to do the full conversion in only one line like below :

function reverseString(inputStr) {
  return inputStr
    .split("")
    .reverse()
    .join("");
}

The output will be the same.

javascript reverse string

So, we have combined all three steps to one in this example.

Conclusion :

We have learnt how to reverse a string in javascript. Reversing a string is widely used functionality in different types of projects. You can also use one loop to pick all characters of a string and create one new string combining them. But this method is easier than the other methods. Try to run the above example and drop a comment below if you have any queries.

Leave a Reply