- Instant help with your JavaScript coding problems

Generate random string in JavaScript

Question:
How to generate random string in JavaScript?
Answer:
function getRandomString(length) {
    const allowedCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const allowedCharacterLength = allowedCharacters.length;

    let result = '';

    for ( let i = 0; i < length; i++ ) {
      result += allowedCharacters.charAt(Math.floor(Math.random() *  allowedCharacterLength));
    }

    return result;
}

const myString = getRandomString(6);
Description:

To generate a simple random string for basic usage you can use the Math.random function in a loop and select characters one by one from a predefined list. With this solution, you can specify the allowed characters, but unfortunately, it cannot be used for serious security implementations due to the limitations of the Math.random function. Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

Share "How to generate random string in JavaScript?"