Random alpha-numeric string in JavaScript? [duplic

2019-01-02 19:27发布

This question already has an answer here:

What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?

17条回答
人气声优
2楼-- · 2019-01-02 19:59

This is cleaner

Math.random().toString(36).substr(2, length)

Example

Math.random().toString(36).substr(2, 5)
查看更多
听够珍惜
3楼-- · 2019-01-02 20:01

I just came across this as a really nice and elegant solution:

Math.random().toString(36).slice(2)
查看更多
初与友歌
4楼-- · 2019-01-02 20:02

Or to build upon what Jar Jar suggested, this is what I used on a recent project (to overcome length restrictions):

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
查看更多
牵手、夕阳
5楼-- · 2019-01-02 20:03

for 32 characters:

for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)
查看更多
唯独是你
6楼-- · 2019-01-02 20:04

Another variation of answer suggested by JAR.JAR.beans

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

By changing multiplicator 1e32 you can change length of random string.

查看更多
大哥的爱人
7楼-- · 2019-01-02 20:06

Nice and simple, and not limited to a certain number of characters:

let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);
查看更多
登录 后发表回答