我想要一个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);

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

(字体兼容)

其他回答

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

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

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

下面这个怎么样。。。这将产生真正随机的值:

function getRandomStrings(length) {
  const value = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const randoms = [];
  for(let i=0; i < length; i++) {
     randoms.push(value[Math.floor(Math.random()*value.length)]);
  }
  return randoms.join('');
}

但如果您在ES6中寻找一个较短的语法:

const getRandomStrings = length => Math.random().toString(36).substr(-length);

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

对于浏览器:

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

对于NodeJS:

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

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

(字体兼容)

我知道每个人都已经做好了,但我想以最轻量级的方式(轻代码,而不是CPU)尝试一下:

函数rand(长度,电流){电流=电流?当前:“”;返回长度?rand(--length,“0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvxyz”.charAt(Math.floor(Math.random()*60))+电流):电流;}console.log(rand(5));

这需要一点时间来理解,但我认为它确实显示了javascript的语法是多么棒。

不区分大小写的字母数字字符:

函数randStr(len){让s=“”;而(s.length<len)s+=Math.random().toString(36).substr(2,len-s.length);返回s;}//用法console.log(randStr(50));

此函数的好处是可以获得不同长度的随机字符串,并确保字符串的长度。

区分大小写的所有字符:

函数randStr(len){让s=“”;而(len--)s+=String.fromCodePoint(Math.floor(Math.random()*(126-33)+33));返回s;}//用法console.log(randStr(50));

自定义字符

函数randStr(len,chars='abc123'){让s=“”;而(len--)s+=字符[Math.floor(Math.random()*chars.length)];返回s;}//用法console.log(randStr(50));console.log(randStr(50,'abc'));console.log(randStr(50,'aab'));//a多于b