在JavaScript中生成随机字符串/字符

我想要一个5个字符串,其中包含从集合中随机选择的字符[a-zA-Z0-9]

用JavaScript做到这一点的最佳方法是什么?

JinJin乐2020/03/09 19:59:38

This one combines many of the answers give.

var randNo = Math.floor(Math.random() * 100) + 2 + "" + new Date().getTime() +  Math.floor(Math.random() * 100) + 2 + (Math.random().toString(36).replace(/[^a-zA-Z]+/g, '').substr(0, 5));

console.log(randNo);

I have been using it for 1 month with great results.

卡卡西神奇2020/03/09 19:59:38

How about something like this: Date.now().toString(36) Not very random, but short and quite unique every time you call it.

Harry逆天2020/03/09 19:59:38

This works for sure

<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>
老丝飞云2020/03/09 19:59:38

I did not find a clean solution for supporting both lowercase and uppercase characters.

Lowercase only support:

Math.random().toString(36).substr(2, 5)

Building on that solution to support lowercase and uppercase:

Math.random().toString(36).substr(2, 5).split('').map(c => Math.random() < 0.5 ? c.toUpperCase() : c).join('');

Change the 5 in substr(2, 5) to adjust to the length you need.

MandyMandyJim2020/03/09 19:59:38

To meet requirement [a-zA-Z0-9] and length=5 use

btoa(Math.random()).substr(5, 5);

Lowercase letters, uppercase letters, and numbers will occur.

LEY神乐2020/03/09 19:59:38

You can loop through an array of items and recursively add them to a string variable, for instance if you wanted a random DNA sequence:

function randomDNA(len) {
  len = len || 100
  var nuc = new Array("A", "T", "C", "G")
  var i = 0
  var n = 0
  s = ''
  while (i <= len - 1) {
    n = Math.floor(Math.random() * 4)
    s += nuc[n]
    i++
  }
  return s
}

console.log(randomDNA(5));

Stafan神乐2020/03/09 19:59:38

Here are some easy one liners. Change new Array(5) to set the length.

Including 0-9a-z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})

Including 0-9a-zA-Z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});
SamGreen2020/03/09 19:59:38

The simplest way is:

(new Date%9e6).toString(36)

This generate random strings of 5 characters based on the current time. Example output is 4mtxj or 4mv90 or 4mwp1

The problem with this is that if you call it two times on the same second, it will generate the same string.

The safer way is:

(0|Math.random()*9e6).toString(36)

This will generate a random string of 4 or 5 characters, always diferent. Example output is like 30jzm or 1r591 or 4su1a

In both ways the first part generate a random number. The .toString(36) part cast the number to a base36 (alphadecimal) representation of it.

神无乐2020/03/09 19:59:38

A newer version with es6 spread operator:

[...Array(30)].map(() => Math.random().toString(36)[2]).join('')

  • The 30 is arbitrary number, you can pick any token length you want
  • The 36 is the maximum radix number you can pass to numeric.toString(), which means all numbers and a-z lowercase letters
  • The 2 is used to pick the 3th index from the random string which looks like this: "0.mfbiohx64i", we could take any index after 0.
逆天西里2020/03/09 19:59:38

function randomstring(L) {
  var s = '';
  var randomchar = function() {
    var n = Math.floor(Math.random() * 62);
    if (n < 10) return n; //1-10
    if (n < 36) return String.fromCharCode(n + 55); //A-Z
    return String.fromCharCode(n + 61); //a-z
  }
  while (s.length < L) s += randomchar();
  return s;
}
console.log(randomstring(5));

Jim小胖米亚2020/03/09 19:59:38

简短,简单且可靠

返回恰好5个随机字符,与此处找到的一些评分最高的答案相反。

Math.random().toString(36).substr(2, 5);
小小Stafan宝儿2020/03/09 19:59:38

最紧凑的解决方案,因为slice它比短substring从字符串末尾减去可以避免该random函数生成的浮点符号

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);

// Using Math.random and Base 36:
console.log(Math.random().toString(36).slice(-5));

// Using new Date and Base 36:
console.log((+new Date).toString(36).slice(-5));

// Using Math.random and Base 64 (btoa):
console.log(btoa(Math.random()).slice(0, 5));

// Using new Date and Base 64 (btoa):
console.log(btoa(+new Date).slice(-7, -2));
console.log(btoa(+new Date).substr(-7, 5));

斯丁JimDavaid2020/03/09 19:59:38

let r = Math.random().toString(36).substring(7);
console.log("random", r);

注意:以上算法具有以下缺点:

  • 由于在对浮点进行字符串化时会删除尾随零,因此它将生成0到6个字符之间的任意位置。
  • 这在很大程度上取决于用于对浮点数进行字符串化的算法,该算法极其复杂。(请参阅论文“如何正确打印浮点数”。)
  • Math.random()根据实现的不同,可能会产生可预测的(“看上去很随机”但不是真正随机的)输出。当您需要保证唯一性或不可预测性时,生成的字符串不适合。
  • 即使它产生了6个均匀随机且不可预测的字符,由于生日悖论,您也可以期望仅生成大约50,000个字符串后看到重复项(sqrt(36 ^ 6)= 46656)