How to reverse a string in javascript

Learn how to effectively reverse a string in javascript.

Strings can be treated as an array like object in javascript and we can use this advantage to perform different actions on it.

Reversing a string with inbuilt methods.

We are going to follow the following approach to reverse the given string.

  • split(): This method will split the string at given expression into an array of characters.
  • reverse(): This method reverses all the elements of an array.
  • join(): This method joins all the elements of the array at a given expression to create a string.

Using all the above methods in line we can reverse any string with ease in javascript.

let str = 'learnersbucket';
let reversed = str.split('').reverse().join('');
console.log(reversed);
//'tekcubsrenrael'

Explanation

Passing '' in split() method will split the each character of the string.

let str = 'learnersbucket';
console.log(str.split(''));
//["l", "e", "a", "r", "n", "e", "r", "s", "b", "u", "c", "k", "e", "t"]

Now once we have an array of character we can reverse it with the reverse() method.

console.log(str.split('').reverse());
//["t", "e", "k", "c", "u", "b", "s", "r", "e", "n", "r", "a", "e", "l"]

We can now create our reversed string by joining all the elements of the array.

console.log(str.split('').reverse().join(''));
//'tekcubsrenrael'

Brute force approach to reverse a string

As we already know strings are an array like object in javascript. We can just simply loop through each character of the string in reverse order and form a reversed string.

let str = 'learnersbucket';
let reversed = '';
for(let i = str.length - 1; i >= 0; i--){
  reversed += str[i];
}

console.log(reversed);
//'tekcubsrenrael'

We can extend the String.prototype to have a method to reverse a string.

//ES5
String.prototype.reverse = function () {
   let reversed = '';
   for(let i = this.length - 1; i >= 0; i--){
      reversed += this[i];
   }
   return reversed;
}

let str = 'learnersbucket';
console.log(str.reverse());
//'tekcubsrenrael'

Extending the same in ES6 with Object.assign.

Object.assign(String.prototype, {
    reverse() {
        let reversed = '';
        for(let i = this.length - 1; i >= 0; i--){
           reversed += this[i];
        }
        return reversed;
    }
});

let str = 'learnersbucket';
console.log(str.reverse());
//'tekcubsrenrael'

Leave a Reply

Your email address will not be published. Required fields are marked *