Generate random string/characters in JavaScript

前端 未结 30 1797
闹比i
闹比i 2020-11-21 06:34

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?

30条回答
  •  名媛妹妹
    2020-11-21 07:30

    Generate a secure random alphanumeric Base-62 string:

    function generateUID(length)
    {
        return window.btoa(Array.from(window.crypto.getRandomValues(new Uint8Array(length * 2))).map((b) => String.fromCharCode(b)).join("")).replace(/[+/]/g, "").substring(0, length);
    }
    
    console.log(generateUID(22)); // "yFg3Upv2cE9cKOXd7hHwWp"
    console.log(generateUID(5)); // "YQGzP"

提交回复
热议问题