我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。

用JavaScript实现这一点的最佳方法是什么?


当前回答

"12345".split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');

//or

String.prototype.rand = function() {return this.split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');};

将生成长度为第一个/调用字符串的随机字母数字字符串

其他回答

生成安全的随机字母数字Base-62字符串:

函数生成UID(长度){return window.btoa(String.fromCharCode(…window.crypto.getRandomValues(新Uint8Array(长度*2))).replace(/[+/]/g,“”).substring(0,长度);}console.log(生成UID(22));//“yFg3Upv2cE9cKOXd7hHwWp”console.log(生成UID(5));//“YQGzP”

这一个结合了许多给出的答案。

var randNo=Math.floor(Math.random()*100)+2+“”+new Date().getTime()+Math.floof(Math.rrandom()*100)+2+(Math.rand().toString(36).replace(/[^a-zA-Z]+/g,'').substr(0,5));console.log(randNo);

我用了一个月,效果很好。

为后代发布ES6兼容版本。如果这是多次调用,请确保将.length值存储到常量变量中。

// USAGE:
//      RandomString(5);
//      RandomString(5, 'all');
//      RandomString(5, 'characters', '0123456789');
const RandomString = (length, style = 'frictionless', characters = '') => {
    const Styles = {
        'all':          allCharacters,
        'frictionless': frictionless,
        'characters':   provided
    }

    let result              = '';
    const allCharacters     = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const frictionless      = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    const provided          = characters;

    const generate = (set) => {
        return set.charAt(Math.floor(Math.random() * set.length));
    };

    for ( let i = 0; i < length; i++ ) {
        switch(Styles[style]) {
            case Styles.all:
                result += generate(allCharacters);
                break;
            case Styles.frictionless:
                result += generate(frictionless);
                break;
            case Styles.characters:
                result += generate(provided);
                break;
        }
    }
    return result;
}

export default RandomString;

Math.random不适合这种情况

服务器端

使用节点加密模块-

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

生成的字符串将是您生成的随机字节的两倍长;编码为十六进制的每个字节是2个字符。20字节将是40个十六进制字符。


客户端

使用浏览器的加密模块crypto.getRandomValues-

通过crypto.getRandomValues()方法,可以获得加密的强随机值。作为参数给出的数组用随机数填充(在其密码意义上是随机的)。

//dec2hex::整数->字符串//即0-255->“00”-“f”功能dec2hex(dec){return dec.toString(16).padStart(2,“0”)}//generateId::整数->字符串函数生成器ID(len){var arr=新Uint8Array((len||40)/2)window.crypto.getRandomValues(arr)return Array.from(arr,dec2hex).join(“”)}console.log(generateId())//“82defcf324571e70b0521d79cce2bf3ffccd69”console.log(generateId(20))//“c1a050a4cd1556948d41”

分步控制台示例-

> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
> arr
Uint8Array(4) [ 0, 0, 0, 0 ]

> window.crypto
Crypto { subtle: SubtleCrypto }

> window.crypto.getRandomValues()
TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed

> window.crypto.getRandomValues(arr)
Uint8Array(4) [ 235, 229, 94, 228 ]

对于IE11支持,您可以使用-

(window.crypto || window.msCrypto).getRandomValues(arr)

有关浏览器覆盖范围,请参阅https://caniuse.com/#feat=getrandomvalues


客户端(旧浏览器)

如果您必须支持旧浏览器,请考虑像uuid这样的东西-

const uuid = require("uuid");
const id = uuid.v4();

// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"

生成包含aA zZ和0-9字符集合的随机字符串。只需使用长度参数调用此函数。

所以要回答这个问题:generateRandomString(5)

generateRandomString(length){
    let result = "", seeds

    for(let i = 0; i < length - 1; i++){
        //Generate seeds array, that will be the bag from where randomly select generated char
        seeds = [
            Math.floor(Math.random() * 10) + 48,
            Math.floor(Math.random() * 25) + 65,
            Math.floor(Math.random() * 25) + 97
        ]
        
        //Choise randomly from seeds, convert to char and append to result
        result += String.fromCharCode(seeds[Math.floor(Math.random() * 3)])
    }

    return result
}

生成不带数字的字符串的版本:

generateRandomString(length){
    let result = "", seeds

    for(let i = 0; i < length - 1; i++){
        seeds = [
            Math.floor(Math.random() * 25) + 65,
            Math.floor(Math.random() * 25) + 97
        ]
        result += String.fromCharCode(seeds[Math.floor(Math.random() * 2)])
    }

    return result
}