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

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


当前回答

这样怎么样:Date.now().toString(36)不是很随意,但每次调用它时都很短且非常独特。

其他回答

function generate(length) {
  var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"];
  var IDtext = "";
  var i = 0;
  while (i < length) {
    var letterIndex = Math.floor(Math.random() * letters.length);
    var letter = letters[letterIndex];
    IDtext = IDtext + letter;
    i++;
  }
  console.log(IDtext)
}

短、简单、可靠

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

Math.random().toString(36).slice(2, 7);
const c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
const s = [...Array(5)].map(_ => c[~~(Math.random()*c.length)]).join('')

如果只需要大写字母(A-Z):

randomAZ(n: number): string {
      return Array(n)
        .fill(null)
        .map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
        .map(a => String.fromCharCode(a))
        .join('')
 }

如果您只希望第一个字母大写(A-Z),其余字母小写(A-Z):

function RandomWord(n: number): string {
    return Array(n)
      .fill(null)
      .map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
      .map((a, i) => i === 0? String.fromCharCode(a) : String.fromCharCode(a+32))
      .join('')
}

喜欢这个SO问题和他们的答案。因此,提出了更具创意的解决方案。我提出了一个封装在函数中的函数,该函数接收要获取的字符串的长度加上一个模式参数,以决定如何编写字符串。

模式是一个3长度的字符串,只接受“1s”和“0s”,它们定义了要在最终字符串中包含的字符子集。它由3个不同的子集([0-9]、[A-B]、[A-B])分组

'100': [0-9]
'010': [A-B]
'101': [0-9] + [a-b]
'111': [0-9] + [A-B] + [a-b]

有8种可能的组合(2^N,其中N:#子集)。“000”模式返回空字符串。

function randomStr(l = 1, mode = '111') {
    if (mode === '000') return '';
    const r = (n) => Math.floor(Math.random() * n);
    const m = [...mode].map((v, i) => parseInt(v, 10) * (i + 1)).filter(Boolean).map((v) => v - 1);
    return [...new Array(l)].reduce((a) => a + String.fromCharCode([(48 + r(10)), (65 + r(26)), (97 + r(26))][m[r(m.length)]]), '')
}

一个简单的用例是:

random = randomStr(50, '101')
// ii3deu9i4jk6dp4gx43g3059vss9uf7w239jl4itv0cth5tj3e
// Will give you a String[50] composed of [0-9] && [a-b] chars only.

这里的主要思想是使用UNICODE表,而不是像我在许多答案中看到的那样随机化十六进制。这种方法的强大之处在于,您可以很容易地将其扩展为包含UNICODE表的其他子集,其中包含一些随机int(16)无法完成的额外代码。