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 was working on a freelance project and I need to create a long random string using JavaScript. I used the following code snippet for that and you can use that code in your project too. Here goes the full source code.

– Function to 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);

Check Demo

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!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top