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

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


当前回答

//返回随机字母

let alpha = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
console.log(alpha.charAt(Math.floor(Math.random() * alpha.length)));

其他回答

改进了上面@Andrew的回答:

Array.from({ length : 1 }, () => Math.random().toString(36)[2]).join('');

随机数的基数36转换是不一致的,因此选择一个标记可以解决这个问题。您可以使用所需的确切长度更改字符串的长度。

这是firefoxchrome代码(插件等)

它可以节省你几个小时的研究时间。

function randomBytes( amount )
{
    let bytes = Cc[ '@mozilla.org/security/random-generator;1' ]

        .getService         ( Ci.nsIRandomGenerator )
        .generateRandomBytes( amount, ''            )

    return bytes.reduce( bytes2Number )


    function bytes2Number( previousValue, currentValue, index, array )
    {
      return Math.pow( 256, index ) * currentValue + previousValue
    }
}

将其用作:

let   strlen   = 5
    , radix    = 36
    , filename = randomBytes( strlen ).toString( radix ).splice( - strlen )

最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:

Math.random().toString(36).slice(-5);

甚至

(+new Date).toString(36).slice(-5);

更新:添加了一种使用btoa方法的方法:

btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);

//使用Math.random和Base 36:console.log(Math.random().toString(36).slice(-5));//使用新的日期和基数36:console.log((+new Date).toString(36).slice(-5));//使用Math.random和Base 64(btoa):console.log(btoa(Math.random()).slice(0,5));//使用新的日期和基数64(btoa):console.log(btoa(+新日期).slice(-7,-2));console.log(btoa(+新日期).substr(-7,5));

Math.random不适合这种情况

服务器端

使用节点加密模块-

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

生成的字符串将是您生成的随机字节的两倍长;编码为十六进制的每个字节是2个字符。20字节将是40个十六进制字符。


客户端

使用浏览器的加密模块crypto.getRandomValues-

通过crypto.getRandomValues()方法,可以获得加密的强随机值。作为参数给出的数组用随机数填充(在其密码意义上是随机的)。

//dec2hex::整数->字符串//即0-255->“00”-“f”功能dec2hex(dec){return dec.toString(16).padStart(2,“0”)}//generateId::整数->字符串函数生成器ID(len){var arr=新Uint8Array((len||40)/2)window.crypto.getRandomValues(arr)return Array.from(arr,dec2hex).join(“”)}console.log(generateId())//“82defcf324571e70b0521d79cce2bf3ffccd69”console.log(generateId(20))//“c1a050a4cd1556948d41”

分步控制台示例-

> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
> arr
Uint8Array(4) [ 0, 0, 0, 0 ]

> window.crypto
Crypto { subtle: SubtleCrypto }

> window.crypto.getRandomValues()
TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed

> window.crypto.getRandomValues(arr)
Uint8Array(4) [ 235, 229, 94, 228 ]

对于IE11支持,您可以使用-

(window.crypto || window.msCrypto).getRandomValues(arr)

有关浏览器覆盖范围,请参阅https://caniuse.com/#feat=getrandomvalues


客户端(旧浏览器)

如果您必须支持旧浏览器,请考虑像uuid这样的东西-

const uuid = require("uuid");
const id = uuid.v4();

// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"

我想这会对你有用:

函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));