我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:
Math.random().toString(36).slice(-5);
甚至
(+new Date).toString(36).slice(-5);
更新:添加了一种使用btoa方法的方法:
btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);
//使用Math.random和Base 36:console.log(Math.random().toString(36).slice(-5));//使用新的日期和基数36:console.log((+new Date).toString(36).slice(-5));//使用Math.random和Base 64(btoa):console.log(btoa(Math.random()).slice(0,5));//使用新的日期和基数64(btoa):console.log(btoa(+新日期).slice(-7,-2));console.log(btoa(+新日期).substr(-7,5));
其他回答
这是肯定的
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>
回顾
许多答案基于技巧Math.random().toString(36),但这种方法的问题是Math.randum并不总是产生以36为基数至少有5个字符的数字。
让testRnd=n=>console.log(`num dec:${n},num base36:${n.toString(36)},string:${n.toString(36,substr(2,5)}`);[Math.random(),//并且远小于0.5。。。0.5,0.50077160493827161,0.5015432098765432,0.5023148148148148,0.5030864197530864,//还有更多。。。。0.9799597050754459].map(n=>测试Rnd(n));console.log('…等等');以下每个示例(第一个除外)的数字结果少于5个字符(不符合OP问题要求)
这里是“生成器”,允许手动查找这些数字
函数base36Todec(十六进制){hex=十六进制拆分(/\./);return(parseInt(hex[1],36))*(36**-hex[1].length)++(parseInt(hex[0],36);}函数calc(十六进制){设dec=base36Todec(十六进制);msg.innerHTML=`dec:<b>${dec}</b><br>十六进制测试:<b>${dec.toString(36)}</b>`} 函数calc2(dec){msg2.innerHTML=`dec:<b>${dec}</b><br>十六进制测试:<b>${(+dec).toString(36)}</b>`} 让init=“0.za1”;inp.value=init;calc(初始化);键入0-1范围内的数字,使用基数36(0-9,a-z),点后少于5位<br><input-oninput=“calc(this.value)”id=“inp”/><div id=“msg”></div><br>如果上面的<i>十六进制测试</i>在点后给出的数字多于5,那么您可以尝试将dec数字复制到下面的字段,并将一些数字连接到dec数字右侧和/或更改最后一个数字-它有时也会产生数字较少的十六进制<br><input-oninput=“calc2(this.value)”/><br><div id=“msg2”></div>
我已经在这里给出了答案,所以我不会在这里提出另一个解决方案
如果可以使用库,Chance.js可能会有所帮助:http://chancejs.com/#string
"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('');};
将生成长度为第一个/调用字符串的随机字母数字字符串
对于包含大小写字母和数字(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个字节(因为字符列表)。