在JavaScript中生成一个随机的字母数字(大写,小写和数字)字符串来用作可能唯一的标识符的最短方法是什么?


当前回答

使用md5库:https://github.com/blueimp/JavaScript-MD5

最短的方法:

md5(随机数学。()

如果你想限制大小为5:

md5 (math . random())。substr (0, 5)

其他回答

随机密钥生成器

keyLength参数是你想要的键的字符长度

function keyGen(keyLength) {
    var i, key = "", characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    var charactersLength = characters.length;

    for (i = 0; i < keyLength; i++) {
        key += characters.substr(Math.floor((Math.random() * charactersLength) + 1), 1);
    }

    return key;
}


keyGen(12)
"QEt9mYBiTpYD"

很好,很简单,而且不局限于一定数量的字符:

let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);

更新: 一行程序解决方案,随机20个字符(字母数字小写):

Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');

或者用lodash更短:

_.times(20, () => _.random(35).toString(36)).join('');

一个取长度的简单函数

getRandomToken(len: number): string {
  return Math.random().toString(36).substr(2, len);
}

如果你传递6,它会生成6位字母数字

我只是发现了一个非常好的优雅的解决方案:

Math.random().toString(36).slice(2)

这个实现的注意事项:

This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros. It won't generate capital letters, only lower-case and numbers. Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique. Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.