Reverse a String in JavaScript

Sunday 28 May 2017

Hello friends, in this post we are going to learn how to reverse a string, though there are so many ways to reverse a string, in this post we will find the best way to reverse a string with high-efficiency and performance. to find the performance of logic to reverse a string I will use performance.now() method.

Below are the contents which we will cover in this post,
  1. Various ways to reverse a string
  2. Comparing the performances of the various ways to reverse a string
  3. Getting the best way to reverse a string
Various ways to reverse a string

As we discussed earlier that there are various ways to reverse a string, we will discuss the various ways to reverse a string  as below,

Way 1: Using Built-in Functions

In this process, we will follow below steps,
  1. Converting string to array using String.prototype.split() method
  2. Reversing the array using Array.prototype.reverse() method
  3. Converting array to string using Array.prototype.join() method
function stringReverse(str){
    var stringToArray  = str.split(" "); // String to Array Conversion
    var reversedArray = stringToArray.reverse(); // Reversing the above Array
    var arrayToString  = reversedArray.join(" "); // Above reversed Array to String
    return arrayToString;
}

All the above code we can write in one line as below,
function stringReverse(str){
    return str.split(" ").reverse().join(" ");
}

Performance :
Below is the performance report of the above function for reversing a string i.e "Reverse a String in JavaScript",
Browser Version First Run(ms) Second Run(ms) Third Run(ms)
Chrome 58.0.3029.110 (64-bit) 0.275 0.04 0.035
IE 10.0.9200.16384 17.0253801 0.052171305 0.021381676
Firefox 53.0.3 (32-bit) 0.1 0.05 0.055

Way 2: Using Decremented For Loop
In this process of reverse the string we will follow below steps,

  1. Run the for loop with decremented order 
  2. Concatenate the each char at each index to a variable 
function stringReverse(str) {
    var reversedString = ""; // Variable having empty string as the value
    // Run the for loop with decremented order
    for (var i = str.length - 1; i >= 0; i--) { 
        reversedString += str[i]; // Concatenate each char to the variable reversedString
    }
    return reversedString;
}

Performance :
Below is the performance report of the above function for reversing a string i.e "Reverse a String in JavaScript",

BrowserVersionFirst Run(ms)Second Run(ms)Third Run(ms)
Chrome58.0.3029.110 (64-bit)0.0250.090.01
IE10.0.9200.1638411.53790.050880.07911
Firefox53.0.3 (32-bit)0.3550.0350.015

These are two basic ways to reverse a string, apart from these two we have more ways but we will learn those on later posts.

No comments:

Post a Comment

 
About Contact Career Advertise Job Support Online Training Acardemic Projects Internship
Copyright © 2016. [ info ].
Design by Herdiansyah Hamzah. & Distributed by Free Blogger Templates
Creative Commons License