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

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


当前回答

短、简单、可靠

返回5个随机字符,而不是此处找到的一些排名最高的答案。

Math.random().toString(36).slice(2, 7);

其他回答

如果可以使用库,Chance.js可能会有所帮助:http://chancejs.com/#string

简单方法:

function randomString(length) {
    let chars = [], output = '';
    for (let i = 32; i < 127; i ++) {
        chars.push(String.fromCharCode(i));
    }
    for (let i = 0; i < length; i ++) {
        output += chars[Math.floor(Math.random() * chars.length )];
    }
    return output;
}

如果您想要更多或更少的字符,请将“127”更改为其他字符。

我想这会对你有用:

函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));

您可以使用Web Crypto的API:

console.log(self.crypto.getRandomValues(新Uint32Array(1))[0])

(此处为原始答案)

短、简单、可靠

返回5个随机字符,而不是此处找到的一些排名最高的答案。

Math.random().toString(36).slice(2, 7);