Generate random string/characters in JavaScript

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9] .

What's the best way to do this with JavaScript?


我认为这会对你有用:

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

console.log(makeid());

Math.random().toString(36).substring(7);

Math.random is bad for this kind of thing

Option 1

If you're able to do this server-side, just use the crypto module

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes will be 40 characters of hex.


Option 2

If you have to do this client-side, perhaps try the uuid module

var uuid = require("uuid");
var id = uuid.v4();

// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"

Option 3

If you have to do this client-side and you don't have to support old browsers, you can do it without dependencies

// dec2hex :: Integer -> String
function dec2hex (dec) {
  return ('0' + dec.toString(16)).substr(-2)
}

// generateId :: Integer -> String
function generateId (len) {
  var arr = new Uint8Array((len || 40) / 2)
  window.crypto.getRandomValues(arr)
  return Array.from(arr, dec2hex).join('')
}

console.log(generateId())
// "82defcf324571e70b0521d79cce2bf3fffccd69"

console.log(generateId(20))
// "c1a050a4cd1556948d41"
链接地址: http://www.djcxy.com/p/2918.html

上一篇: 在特定范围内使用JavaScript生成随机整数?

下一篇: 在JavaScript中生成随机字符串/字符