Creating a real UUIDv4 in JS usually requires a library. The new https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID can be used in the browser.
But how hard is it to create a valid UUIDv4? As it turns out, not very!
The following is all that is needed for a version 4 UUID (including correctly setting the so called M
and N
bits):
const generateUUID = () => "10000000-1000-4000-8000-100000000000".replace(/[018]/g, s => (s ^ Math.random() * 256 & 15 >> s / 4).toString(16));
This can be seen in action at https://gist.pother.ca/4a2b95623519e74b63d9485a4311ac3c