我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
npm模块anyid提供了灵活的API来生成各种字符串ID/代码。
const id = anyid().encode('Aa0').length(5).random().id();
其他回答
function randomString (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
while (strLength--) { // (note, fixed typo)
result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
}
return result.join('');
}
这是最干净的了。它也很快,http://jsperf.com/ay-random-string.
不区分大小写的字母数字字符:
函数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
我知道每个人都已经做好了,但我想以最轻量级的方式(轻代码,而不是CPU)尝试一下:
函数rand(长度,电流){电流=电流?当前:“”;返回长度?rand(--length,“0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvxyz”.charAt(Math.floor(Math.random()*60))+电流):电流;}console.log(rand(5));
这需要一点时间来理解,但我认为它确实显示了javascript的语法是多么棒。
这是Coffeescapet版本的一行代码
genRandomString = (length,set) -> [0...length].map( -> set.charAt Math.floor(Math.random() * set.length)).join('')
用法:
genRandomString 5, 'ABCDEFTGHIJKLMNOPQRSTUVWXYZ'
输出:
'FHOOV' # random string of length 5 in possible set A~Z
同样基于doubletap的答案,该方法处理任意长度的随机所需字符(仅限小写),并不断生成随机数,直到收集到足够的字符。
function randomChars(len) {
var chars = '';
while (chars.length < len) {
chars += Math.random().toString(36).substring(2);
}
// Remove unnecessary additional characters.
return chars.substring(0, len);
}