Home Programs How to Generate Random Strings in JavaScript

How to Generate Random Strings in JavaScript

In this example we show you how to generate random strings in JavaScript

Example 1

We will define a list of characters which will include lower and upper case A – Z characters and numbers 0 – 9

// program to generate random strings
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) 
{
    let result = ' ';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) 
    {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

console.log(generateString(10));
console.log(generateString(10));
console.log(generateString(10));

 

When you run this you will see something like this, here are 3 runs as above

RUqq56A3QU
dlxHceRtCe
gXVhZMQCp3

You may also like