小能豆

Generate random string/characters in JavaScript

javascript

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What’s the best way to do this with JavaScript?


阅读 219

收藏
2023-12-29

共1个答案

小能豆

You can generate a random 5-character string from the set [a-zA-Z0-9] in JavaScript using the following function:

function generateRandomString() {
    const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let randomString = '';

    for (let i = 0; i < 5; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        randomString += characters.charAt(randomIndex);
    }

    return randomString;
}

// Example usage
const randomString = generateRandomString();
console.log(randomString);

This function uses a string characters that contains all the valid characters. It then iterates through a loop five times, randomly selecting a character from the set and appending it to the randomString. The final result is a 5-character random string composed of characters from [a-zA-Z0-9].

2023-12-29