我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
非常简单
function getRandomColor(){
var color='';
while(color.length<6){
color=Math.floor(Math.random()*16777215).toString(16);
}
return '#'+color;
}
其他回答
这一个结合了许多给出的答案。
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);
我用了一个月,效果很好。
从字符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;
}
这里有一种不同的方法,按基数固定长度,不使用RegExp替换lack(基于@bendytree的答案);
function rand(base) {
// default base 10
base = (base >= 2 && base <= 36) ? base : 10;
for (var i = 0, ret = []; i < base; i++) {
ret[i] = ((Math.random() * base) | 0).toString(base)
// include 0-9a-zA-Z?
// [Math.random() < .5 ? 'toString' : 'toUpperCase']();
}
return ret.join('');
}
带有es6排列运算符的更新版本:
[…数组(30)].map(()=>Math.random().toString(36)[2]).join(“”)
30是一个任意数字,您可以选择所需的任何令牌长度36是可以传递给numeric.toString()的最大基数,表示所有数字和a-z小写字母2用于从如下所示的随机字符串中选择第三个索引:“0.mfbiohx64i”,我们可以取0之后的任何索引。
对于包含大小写字母和数字(0-9a-zA-Z)的字符串,这可能是缩小效果最好的版本:
function makeId(length) {
var id = '';
var rdm62;
while (length--) {
// Generate random integer between 0 and 61, 0|x works for Math.floor(x) in this case
rdm62 = 0 | Math.random() * 62;
// Map to ascii codes: 0-9 to 48-57 (0-9), 10-35 to 65-90 (A-Z), 36-61 to 97-122 (a-z)
id += String.fromCharCode(rdm62 + (rdm62 < 10 ? 48 : rdm62 < 36 ? 55 : 61))
}
return id;
}
此函数的内容缩小到97个字节,而顶部答案需要149个字节(因为字符列表)。