我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
我没有找到支持小写和大写字符的干净解决方案。
仅小写支持:
Math.random().toString(36).substr(2,5)
基于该解决方案,支持小写和大写:
Math.random().toString(36).substr(2,5).split(“”).map(c=>Math.randm()<0.5?c.toUpperCase():c).jjoin(“”);
更改substr(2,5)中的5以调整到所需的长度。
其他回答
假设您使用underscorejs,就可以在两行中优雅地生成随机字符串:
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var random = _.sample(possible, 5).join('');
"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('');};
将生成长度为第一个/调用字符串的随机字母数字字符串
如果任何人对一个一次性分配内存的单行程序(虽然为了方便起见,没有格式化为这样)感兴趣(但请注意,对于小字符串,这实际上无关紧要),下面是如何做到的:
Array.apply(0, Array(5)).map(function() {
return (function(charset){
return charset.charAt(Math.floor(Math.random() * charset.length))
}('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));
}).join('')
您可以用所需字符串的长度替换5。感谢@AriyaHidayat在本文中提供的解决方案,该解决方案解决了array(5)创建的稀疏数组上的map函数不工作的问题。
从字符a-Za-z0-9中随机化字符串的另一种好方法:
function randomString(length) {
if ( length <= 0 ) return "";
var getChunk = function(){
var i, //index iterator
rand = Math.random()*10e16, //execute random once
bin = rand.toString(2).substr(2,10), //random binary sequence
lcase = (rand.toString(36)+"0000000000").substr(0,10), //lower case random string
ucase = lcase.toUpperCase(), //upper case random string
a = [lcase,ucase], //position them in an array in index 0 and 1
str = ""; //the chunk string
b = rand.toString(2).substr(2,10);
for ( i=0; i<10; i++ )
str += a[bin[i]][i]; //gets the next character, depends on the bit in the same position as the character - that way it will decide what case to put next
return str;
},
str = ""; //the result string
while ( str.length < length )
str += getChunk();
str = str.substr(0,length);
return str;
}
这是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