How to reverse a string in JavaScript [Step-by-step]

Reading time icon 6 min. read


Readers help support Windows Report. We may get a commission if you buy through our links. Tooltip Icon

Read our disclosure page to find out how can you help Windows Report sustain the editorial team. Read more

Key notes

  • Knowing how to reverse a string in JavaScript is an essential skill, and this guide provides you with step-by-step instructions.
  • The first method that can be applied in this case is to convert the string into an array and reverse it.
  • Explore our thorough Developer Tools Hub for more useful information on this topic.
  • Don't hesitate to bookmark our extensive Javascript section for more easy-to-follow guides.
Reversing your string with Javascript

A palindrome is a word or list of characters that read the same when reversed. A good example of this is the word ‘RADAR’.

The easiest way to check for a palindrome in JavaScript is to create a copy of the original string, reverse it, and then compare it. If you want to build an algorithm that does this effectively, you’ll need to learn how to reverse a string in JavaScript. In this guide, you’ll learn how.

How do I reverse a string with JavaScript?

1. Convert it into an array and reverse it

  1. Split your string into an array of substrings using the split() method from the String object class. The split method requires a string as its argument. In this case, you’ll use an empty string. So the method should look like this:
    split("")
  2. Reverse the order of the array using the reverse() method.
  3. Convert the array back into a string using the join() method. Much like the split method, the join method requires a string as an argument. Once again, you’ll use an empty string:
    join("")

The best way to implement the above steps is through a function. Here’s a quick source code example that you can copy, test, and modify:

<!DOCTYPE html>
<html>
<body>
<H2> The Great Reverso! </H2>
<p>Current String: "Reverse this String!"</p>
<button onclick="myFunction()">Reverse</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Reverse This String!";
var res = str.split(""); //Split the string into an array of characters
res.reverse(); //Reverse the order of the array of characters
str = res.join("");
document.getElementById("demo").innerHTML = str; //Attach the string to the HTML demo
}
</script>
</body>
</html>

In the above example, we create a function that reverses a hard-coded string and then sets a document element to it.  The function is then called from a button labeled ‘Reverse’.

There are numerous ways you can shorten and modify this code. For instance, instead of assigning the joined string to the str variable, you can reassign it to to the res variable and then point the  demo HTML document element to it i.e.

res = res.join("");
document.getElementById("demo").innerHTML = res;

Alternatively, you can condense all three steps into a single line:

var res = str.split("").reverse().join("");

Either way, the results should be the same:

reverse-javascript-string-example


Want to learn JavaScript even faster? Learn why you should download JavaScript Code by reading this article!


2. Reverse the string in JavaScript using a for loop

  1. Create a new empty string variable that will house the reversed string.
    var reverseString = "";
  2. Construct a for loop with the following characteristics:
    • Initializer: initialize a counter whose value is the length of the string to be reversed subtracted by 1.
    • Condition: make sure that the counter is greater than or equal to 0.
    • Iteration: the counter should decrement with every successful loop.
    • The body of the for loop should add a character from the original string to what will become the reversed string while using the for loop counter to set the character position.
      for (var i = fwdStri.length - 1; i >= 0; i--) { 
             reverseString = newString + fwdStr[i]; 
      }

Once again, you should apply the above operation in a function within scripting tags. Whether you want to include the JavaScript as an external file or embedded code is up to you. Here’s how the above solution looks in action:

<!DOCTYPE html>
<html>
<body>
<H2> The Great Reverso! </H2>
<p>Current String: "Reverse this String!"</p>
<button onclick="myFunction()">Reverse</button>
<p id="demo"></p>
<script>
function myFunction() {
var fwdString = "Reverse this String!";
var reverseString = "";

for (var i = fwdString.length - 1; i >= 0; i--) {

reverseString += fwdString[i]; //Alternative to newString + fwdString[i]

}

document.getElementById("demo").innerHTML = reverseString;

}
</script>
</body>
</html>

The above code works by looping through your original string in reverse and clones it character by character. If you’re not interested in explicitly casting your string into an array, then you may find this solution more suited to your goals.


3. Reverse the string in JavaScript using recursion

  1. Create a new function with a string as its parameter e.g.
    function reverseString(str) {
  2. Within the body of the function, create an if statement that checks if the string passed to the function is empty. If true, it should return an empty string e.g.
    if (str === "")
    return "";
  3. Add an else statement.
  4. In the body of the else statement, return a recursive call to the current method with a substring of the method’s string parameter, starting from the second character i.e str.substr(1). Append the first letter of the new substring e.g.
    else
    
    return reverseString(str.substr(1)) + str.charAt(0);

You should call this method from another function that’s responsible for displaying the results. The complete code should look something like this:

<!DOCTYPE html>
<html>
<body>
<H2> The Great Reverso! </H2>
<p>Current String: "Reverse this String!"</p>
<button onclick="myFunction()">Reverse</button>
<p id="demo"></p>
<script>


function myFunction() {

var str = this.reverseString("Reverse this String!");
document.getElementById("demo").innerHTML = str;

}

function reverseString(str) {
if (str === "")
return "";

else

return reverseString(str.substr(1)) + str.charAt(0);



}
</script>
</body>
</html>

Recursion works a lot like a for loop, but you’re tricking JavaScript‘s logic to work for you. Instead of appending characters to the end of the string, it attaches it to the front with each loop. Nevertheless, the results are much the same.

The above examples can be tested by using Windows Notepad and a web browser. However, we suggest using a cross-platform code editor or an integrated development environment to save yourself some time.

How to reverse a string in a Javascript is a common interview question. Therefore, understanding it may be imperative to your success as a software developer.

Nonetheless, let us know which method worked best for you in the comments below. As always, thank you for reading.

[wl_navigator]

More about the topics: Javascript

User forum

0 messages