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

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


当前回答

对于包含大小写字母和数字(0-9a-zA-Z)的字符串,这可能是缩小效果最好的版本:

function makeId(length) {
  var id = '';
  var rdm62;
  while (length--) {
   // Generate random integer between 0 and 61, 0|x works for Math.floor(x) in this case 
   rdm62 = 0 | Math.random() * 62; 
   // Map to ascii codes: 0-9 to 48-57 (0-9), 10-35 to 65-90 (A-Z), 36-61 to 97-122 (a-z)
   id += String.fromCharCode(rdm62 + (rdm62 < 10 ? 48 : rdm62 < 36 ? 55 : 61)) 
  }
  return id;
}

此函数的内容缩小到97个字节,而顶部答案需要149个字节(因为字符列表)。

其他回答

加密强

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

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评论,我更新代码以获得任意长密码

最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:

Math.random().toString(36).slice(-5);

甚至

(+new Date).toString(36).slice(-5);

更新:添加了一种使用btoa方法的方法:

btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);

//使用Math.random和Base 36:console.log(Math.random().toString(36).slice(-5));//使用新的日期和基数36:console.log((+new Date).toString(36).slice(-5));//使用Math.random和Base 64(btoa):console.log(btoa(Math.random()).slice(0,5));//使用新的日期和基数64(btoa):console.log(btoa(+新日期).slice(-7,-2));console.log(btoa(+新日期).substr(-7,5));

这是我用过的。这是一对夫妇的组合。我在循环中使用它,它生成的每个ID都是唯一的。它可能不是5个字符,但它保证是唯一的。

var newId =
    "randomid_" +
    (Math.random() / +new Date()).toString(36).replace(/[^a-z]+/g, '');

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

函数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

一个衬垫[a-z]:

String.fromCharCode(97 + Math.floor(Math.random() * 26))