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

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


当前回答

不区分大小写的字母数字字符:

函数randStr(len){让s=“”;而(s.length<len)s+=Math.random().toString(36).substr(2,len-s.length);返回s;}//用法console.log(randStr(50));

此函数的好处是可以获得不同长度的随机字符串,并确保字符串的长度。

区分大小写的所有字符:

函数randStr(len){让s=“”;而(len--)s+=String.fromCodePoint(Math.floor(Math.random()*(126-33)+33));返回s;}//用法console.log(randStr(50));

自定义字符

函数randStr(len,chars='abc123'){让s=“”;而(len--)s+=字符[Math.floor(Math.random()*chars.length)];返回s;}//用法console.log(randStr(50));console.log(randStr(50,'abc'));console.log(randStr(50,'aab'));//a多于b

其他回答

这一个结合了许多给出的答案。

var randNo=Math.floor(Math.random()*100)+2+“”+new Date().getTime()+Math.floof(Math.rrandom()*100)+2+(Math.rand().toString(36).replace(/[^a-zA-Z]+/g,'').substr(0,5));console.log(randNo);

我用了一个月,效果很好。

"12345".split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');

//or

String.prototype.rand = function() {return this.split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');};

将生成长度为第一个/调用字符串的随机字母数字字符串

如果可以使用库,Chance.js可能会有所帮助:http://chancejs.com/#string

这将在变量c中存储5个字母数字字符。

for(var c = ''; c.length < 5;) c += Math.random().toString(36).substr(2, 1)

我想这会对你有用:

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