我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
一个衬垫[a-z]:
String.fromCharCode(97 + Math.floor(Math.random() * 26))
其他回答
//返回随机字母
let alpha = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
console.log(alpha.charAt(Math.floor(Math.random() * alpha.length)));
这里有一些简单的一行。更改新阵列(5)以设置长度。
包括0-9a-z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})
包括0-9a-zA-Z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});
ES6编码(0-9a-z)
Array(5).fill().map(n=>(Math.random()*36|0).toString(36)).join('')
假设您使用underscorejs,就可以在两行中优雅地生成随机字符串:
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var random = _.sample(possible, 5).join('');
生成任意数量的十六进制字符(例如32):
(function(max){let r='';for(let i=0;i<max/13;i++)r+=(Math.random()+1).toString(16).substring(2);return r.substring(0,max).toUpperCase()})(32);
不区分大小写的字母数字字符:
函数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