我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。

用JavaScript实现这一点的最佳方法是什么?


当前回答

如果您无法键入字符集,使用String.fromCharCode和范围内的Math.random可以在任何Unicode代码点范围内创建随机字符串。例如,如果您想要17个随机藏文字符,可以输入ranstr(17,0xf00,0xfff),其中(0xf00,0xff)对应于藏文Unicode块。在我的实现中,如果不指定代码点范围,生成器将输出ASCII文本。函数ranchar(a,b){a=(a==未定义?0:a);b=(b===未定义?127:b);return String.fromCharCode(Math.floor(Math.random()*(b-a)+a));}函数transtr(len,a,b){a=a||32;var结果=“”;对于(var i=0;i<len;i++){结果+=ranchar(a,b)}返回结果;}//以下是随机Unicode块的一些示例console.log('拉丁语基本块:'+transtr(10,0x000,0x007f))console.log('拉丁语-1增补块:'+transtr(10,0x080,0x0ff))console.log('货币符号块中:'+transtr(10,0x20a0,0x20cf))console.log('在类字母符号块中:'+transtr(10,0x2100,0x214f))console.log('在Dingbats块中:'+transtr(10,0x2700,0x27bf))

其他回答

function generateRandomStringLettersAndNumbers(maxLength): string {
  return crypto.randomBytes(maxLength).toString('hex').substring(0, maxLength);
}

如果您使用的是Lodash或Undercore,那么非常简单:

var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');

这是第一个答案的测试脚本(谢谢@csharptest.net)

该脚本运行makeid()100万次,如您所见,5不是一个非常独特的脚本。以10的字符长度运行它是非常可靠的。我已经运行了大约50次,还没有看到重复的:-)

注意:节点堆栈大小限制超过了大约400万,因此您无法运行这500万次,它永远无法完成。

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

ids ={}
count = 0
for (var i = 0; i < 1000000; i++) {
    tempId = makeid();
    if (typeof ids[tempId] !== 'undefined') {
        ids[tempId]++;
        if (ids[tempId] === 2) {
            count ++;
        }
        count++;
    }else{
        ids[tempId] = 1;
    }
}
console.log("there are "+count+ ' duplicate ids');

一行使用地图,可以完全控制长度和字符。

const rnd = (len, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') => [...Array(len)].map(() => chars.charAt(Math.floor(Math.random() * chars.length))).join('')

console.log(rnd(12))

回顾

许多答案基于技巧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>

我已经在这里给出了答案,所以我不会在这里提出另一个解决方案