Generate a string of random characters
I want a string of fixed length, composed of characters picked randomly from a set of characters e.g. [a-zA-Z0-9].
How can I do this with JavaScript?
I want a string of fixed length, composed of characters picked randomly from a set of characters e.g. [a-zA-Z0-9].
How can I do this with JavaScript?
先自己寫寫看怎麼答,再往下對照重點答案。只存在你這台瀏覽器。
I think this will work for you:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(5));
//Can change 7 to 2 for longer results.
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);
Note: The above algorithm has the following weaknesses:
Math.random() may produce predictable ("random-looking" but not really random) output depending on the implementation. The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.Math.random is bad for this kind of thing
server side (node, bun)
Use node crypto module -
esm -
import * as crypto from "node:crypto";
const id = crypto.randomBytes(20).toString('hex');
console.log(id)
// "bb5dc8842ca31d4603d6aa11448d1654"
or cjs -
const crypto = require("crypto");
const id = crypto.randomBytes(20).toString('hex');
console.log(id)
// "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.
client side (browser)
Use the browser's crypto module -
const id = window.crypto.randomUUID()
console.log(id)
// bd4d099b-3d39-4aad-a59c-c45dfac8eaf0
The
crypto.getRandomValues()method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).
// dec2hex :: Integer -> String
// i.e. 0-255 -> '00'-'ff'
function dec2hex (dec) {
return dec.toString(16).padStart(2, "0")
}
// 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"
A step-by-step console example -
> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
> arr
Uint8Array(4) [ 0, 0, 0, 0 ]
> window.crypto
Crypto { subtle: SubtleCrypto }
> window.crypto.getRandomValues()
TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed
> window.crypto.getRandomValues(arr)
Uint8Array(4) [ 235, 229, 94, 228 ]
For IE11 support you can use -
(window.crypto || window.msCrypto).getRandomValues(arr)
For browser coverage see https://caniuse.com/#feat=getrandomvalues
client side (old browsers)
If you must support old browsers, consider something like uuid -
const uuid = require("uuid");
const id = uuid.v4();
// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"