JavaScript Program to Generate Random String/Characters.

Hey guys, in this example we will learn how to generate random string of any size using random characters from A-Z, a-z, and 0-9.


Code:


// Declare all required characters
const all_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

function generateRandomString(length) {
    let result_string = '';
    const characters_length = all_characters.length;
    for ( let i = 0; i < length; i++ ) {
        result_string += all_characters.charAt(Math.floor(Math.random() * characters_length));
    }

    return result_string;
}

console.log(generateRandomString(8));     
    

Output:

DqYNH6Yb

In the example 1, we used Math.random() method which returns a random number/characters from the specified characters (in this case A-Z, a-z, 0-9).

We have used the for loop is used to iterate through the number which is passed into the generateRandomString() function. During each iteration/loop, a random character is generated from specified string and is added to resulting string.

The generated output will be different each time we execute generateRandomString() function.

To view the code on codepen - Check it out here


Post a Comment

0 Comments