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


当前回答

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

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

其他回答

或者根据Jar Jar的建议,这是我在最近的一个项目中使用的方法(以克服长度限制):

var randomString = function (len, bits)
{
    bits = bits || 36;
    var outStr = "", newStr;
    while (outStr.length < len)
    {
        newStr = Math.random().toString(bits).slice(2);
        outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
    }
    return outStr.toUpperCase();
};

Use:

randomString(12, 16); // 12 hexadecimal characters
randomString(200); // 200 alphanumeric characters

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

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.

beans建议的另一种答案变体

(Math.random()*1e32).toString(36)

通过改变乘数1e32,你可以改变随机字符串的长度。

当我看到这个问题时,我想到了我必须生成uuid的时候。我不能把代码的功劳,因为我确信我在stackoverflow上找到了它。如果你不想在字符串中使用破折号,那就去掉破折号。函数如下:

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid.toUpperCase();
}

小提琴:http://jsfiddle.net/nlviands/fNPvf/11227/

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

最短的方法:

md5(随机数学。()

如果你想限制大小为5:

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