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

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


当前回答

试试这个,我每次都用的:

函数myFunction(){var hash=“abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789”;var random8=“”;对于(变量i=0;i<5;i++){random8+=哈希[parseInt(Math.random()*hash.length)];}控制台日志(random8);document.getElementById(“demo”).innerHTML=“您的5个字符串==>”+random8;} <!DOCTYPE html><html><body><p>单击按钮生成5个字符的随机字符串</p><button onclick=“myFunction()”>单击我</button><p id=“demo”></p></body></html>

其他回答

function randomString (strLength, charSet) {
    var result = [];
    
    strLength = strLength || 5;
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    
    while (strLength--) { // (note, fixed typo)
        result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
    }
    
    return result.join('');
}

这是最干净的了。它也很快,http://jsperf.com/ay-random-string.

对于包含大小写字母和数字(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个字节(因为字符列表)。

这是doubletap答案的稍微改进版本。当Math.random()返回0、0.5、0.25、0.125等时,它会考虑gertas对案例的评论。

((Math.random()+3*Number.MIN_VALUE)/Math.PI).toString(36).slice(-5)

它防止零被传递给toString,我将最小的浮点值添加到Math.random()。它确保传递给toString的数字有足够的数字,通过除以一个几乎不合理的数字。

我只需要编写一个简单的包来生成具有给定大小、种子和掩码的随机令牌。仅供参考。

@sibevin/随机令牌-https://www.npmjs.com/package/@sibevin/随机令牌

import { RandomToken } from '@sibevin/random-token'

RandomToken.gen({ length: 32 })
// JxpwdIA37LlHan4otl55PZYyyZrEdsQT

RandomToken.gen({ length: 32, seed: 'alphabet' })
// NbbtqjmHWJGdibjoesgomGHulEJKnwcI

RandomToken.gen({ length: 32, seed: 'number' })
// 33541506785847193366752025692500

RandomToken.gen({ length: 32, seed: 'oct' })
// 76032641643460774414624667410327

RandomToken.gen({ length: 32, seed: 'hex' })
// 07dc6320bf1c03811df7339dbf2c82c3

RandomToken.gen({ length: 32, seed: 'abc' })
// bcabcbbcaaabcccabaabcacbcbbabbac

RandomToken.gen({ length: 32, mask: '123abcABC' })
// vhZp88dKzRZGxfQHqfx7DOL8jKTkWUuO

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

对于浏览器:

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

对于NodeJS:

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

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

(字体兼容)