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

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


当前回答

为了满足要求[a-zA-Z0-9]和5个字符的长度,使用

对于浏览器:

btoa(Math.random().toString()).substring(10,15);

对于NodeJS:

Buffer.from(Math.random().toString()).toString("base64").substring(10,15);

将出现小写字母、大写字母和数字。

(字体兼容)

其他回答

npm模块anyid提供了灵活的API来生成各种字符串ID/代码。

const id = anyid().encode('Aa0').length(5).random().id();

简单方法:

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”更改为其他字符。

带有es6排列运算符的更新版本:

[…数组(30)].map(()=>Math.random().toString(36)[2]).join(“”)

30是一个任意数字,您可以选择所需的任何令牌长度36是可以传递给numeric.toString()的最大基数,表示所有数字和a-z小写字母2用于从如下所示的随机字符串中选择第三个索引:“0.mfbiohx64i”,我们可以取0之后的任何索引。

如果您使用的是Lodash或Undercore,那么非常简单:

var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');

加密强

如果您想获得满足您要求的加密强字符串(我看到的答案使用了这个,但给出了无效答案),请使用

let pass = n=> [...crypto.getRandomValues(new Uint8Array(n))]
   .map((x,i)=>(i=x/255*61|0,String.fromCharCode(i+(i>9?i>35?61:55:48)))).join``

let pass=n=>[…crypto.getRandomValues(新Uint8Array(n))].map((x,i)=>(i=x/255*61|0,String.fromCharCode(i+(i>9?i>35?61:55:48))).join``console.log(通过(5));

更新:感谢Zibri评论,我更新代码以获得任意长密码