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

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


当前回答

随机unicode字符串

此方法将返回一个随机字符串,其中包含任何受支持的unicode字符,这不是OP要求的100%,而是我想要的:

function randomUnicodeString(length){
    return Array.from({length: length}, ()=>{
        return String.fromCharCode(Math.floor(Math.random() * (65536)))
    }).join('')
}

根本原因

这是谷歌搜索“随机字符串javascript”时的最高结果,但OP只要求a-zA-Z0-9。

其他回答

下面这个怎么样。。。这将产生真正随机的值:

function getRandomStrings(length) {
  const value = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const randoms = [];
  for(let i=0; i < length; i++) {
     randoms.push(value[Math.floor(Math.random()*value.length)]);
  }
  return randoms.join('');
}

但如果您在ES6中寻找一个较短的语法:

const getRandomStrings = length => Math.random().toString(36).substr(-length);

随机unicode字符串

此方法将返回一个随机字符串,其中包含任何受支持的unicode字符,这不是OP要求的100%,而是我想要的:

function randomUnicodeString(length){
    return Array.from({length: length}, ()=>{
        return String.fromCharCode(Math.floor(Math.random() * (65536)))
    }).join('')
}

根本原因

这是谷歌搜索“随机字符串javascript”时的最高结果,但OP只要求a-zA-Z0-9。

简单方法:

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”更改为其他字符。

function generate(length) {
  var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"];
  var IDtext = "";
  var i = 0;
  while (i < length) {
    var letterIndex = Math.floor(Math.random() * letters.length);
    var letter = letters[letterIndex];
    IDtext = IDtext + letter;
    i++;
  }
  console.log(IDtext)
}
[..."abcdefghijklmnopqrsuvwxyz0123456789"].map((e, i, a) => a[Math.floor(Math.random() * a.length)]).join('')