How to invert a string in JavaScript

January 27, 2022

How to invert a string in JavaScript

In this article, we will learn how to invert a string in JavaScript language, in an easy way, using methods that exist in the language itself.

invert a string in JavaScript cover

Hey you all programmers, how are you? Let’s learn more about JavaScript!

The simplest way to invert a string is using a sequence of methods, which may not be the most performing alternative.

But it solves the problem well and simply

The idea is to use the split method, to separate all the characters, followed by the reverse method, which will reverse the array created by split

Finally we will use join, to rejoin the array into a string and deliver it to us inversely

Let’s see it in practice:

let test = "Testando uma string";

let inverted = teste.split("").reverse().join("");

console.log(inverted );

We will then have the following output:

gnirts amu odnatseT

If we are opting for performance, we can opt for a function using a loop

See the example:

function invertString(str) {
 var o = '';
 for (var i = str.length - 1; i >= 0; i--) {
  o += str[i];
 return o;

console.log(invertString("Testing inversion"));

You should choose this method if you are looking for more performing  code, that is, one that runs faster

Also note that for one of these ways to impact performance, the use must be very intense and the number of characters in the string very large

If they are applications to solve simple problems, use the first option


In this article we learned  how to invert a string with the JavaScript language

Two ways to perform this action were discussed, one using a set of methods, which solves the problem but ends up being less performing

And the other is a simple loop that reallocates characters, and also has better performance

Want to learn more about JS? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x