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

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


当前回答

通过回答Gertas和Dragon提出的问题,扩展Doubletap的优雅示例。只需添加一个while循环来测试那些罕见的空情况,并将字符限制为五个。

function rndStr() {
    x=Math.random().toString(36).substring(7).substr(0,5);
    while (x.length!=5){
        x=Math.random().toString(36).substring(7).substr(0,5);
    }
    return x;
}

这里有一个jsfiddle提示您一个结果:http://jsfiddle.net/pLJJ7/

其他回答

例如,如果你想要一个随机的DNA序列,你可以循环遍历一个项目数组并递归地将它们添加到字符串变量中:

功能随机DNA(len){len=长度||100var nuc=新阵列(“A”、“T”、“C”、“G”)变量i=0变量n=0s=“”而(i<=len-1){n=数学楼层(Math.random()*4)s+=努克[n]我++}返回s}console.log(随机DNA(5));

非常简单

function getRandomColor(){
  var color='';
  while(color.length<6){
    color=Math.floor(Math.random()*16777215).toString(16);
  }
  return '#'+color;
}

我使用var randId='rand'+new Date().getTime();

简单方法:

function randomString(length) {
    let chars = [], output = '';
    for (let i = 32; i < 127; i ++) {
        chars.push(String.fromCharCode(i));
    }
    for (let i = 0; i < length; i ++) {
        output += chars[Math.floor(Math.random() * chars.length )];
    }
    return output;
}

如果您想要更多或更少的字符,请将“127”更改为其他字符。

以下代码将使用npm包加密随机字符串生成大小为[a-zA-Z0-9]的加密安全随机字符串。使用以下方法安装:

npm install crypto-random-string

要在集合[a-zA-Z0-9]中获得30个字符的随机字符串:

const cryptoRandomString = require('crypto-random-string');
cryptoRandomString({length: 100, type: 'base64'}).replace(/[/+=]/g,'').substr(-30);

摘要:我们正在替换一个大的随机base64字符串中的/,+,=,并获取最后N个字符。

PS:在子字符串中使用-N