How to Generate Random String in JavaScript

How to Generate Random String in JavaScript

Generating random string in JavaScript is extremely simple. Last day, I worked on my freelance project and I need to create a long random string using JavaScript. As I said before, it’s simple but bit tricky. I thought I can share that snippets, so that you can use that code in your project too. So let’s get started –

– Function For Generate Random String:

function generate_random_string ( string_length ) {

    // If string length is not defined, by default we set it's value as 21
    if( typeof (string_length) == 'undefined') {

        string_length = 21;

    }

    // Initialize random string
    var random_string = " ";

    var charset = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    // Create a for loop
    for( var i=0; i < string_length; i++ ) {

        random_string += charset.charAt(Math.floor(Math.random() * charset.length));

    }

    return random_string;

}

// Call The Function to generate a random string of 30 characters in length

generate_random_string(30);

Enjoy!

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Share It

Related Posts