Skip to content

Instantly share code, notes, and snippets.

@intech
Last active October 10, 2021 03:12
Show Gist options
  • Select an option

  • Save intech/cf00686cc49cb3af2b224be4a80ae5e5 to your computer and use it in GitHub Desktop.

Select an option

Save intech/cf00686cc49cb3af2b224be4a80ae5e5 to your computer and use it in GitHub Desktop.
Random string/uuid/id/etc

Unique hex-string (time+random) with fixed length 11:

(Math.round(Math.random() * 0x10000) + Date.now()).toString(16)
// 16c8e982dcd
// 16c95dc3c76
// 16cb7307195

Unique string (time+random) with fixed length 8:

(Math.round(Math.random() * 0x100000000) + Date.now()).toString(36)
// jzo8uryk
// jzc7u5vm
// jzfbz0b5

Unique hex-string random with fixed length 7:

(~~(Math.random()*1e8)).toString(16)
// 1fa56f1
// 29b5c8d
// 55f1f31

Unique string random with fixed length 5:

(~~(Math.random()*1e8)).toString(36)
// o2ex6
// 1cg5vi
// 1mzmpz

Generate UUIDv4

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,(c,r)=>('x'==c?(r=Math.random()*16|0):(r&0x3|0x8)).toString(16))
// 9bb4f863-4957-495a-b78a-cde1bff363c5
// bbf49198-72de-4d97-bfa2-5486d198577d
// c637c280-3596-4bb6-b953-52fab5280a9f
([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,c=>(c^crypto.getRandomValues(new Uint8Array(1))[0]&15 >> c/4).toString(16))
// 0b01690f-b53c-4cb6-b341-0cd6c3eda247
// a9819445-1690-4c01-bbd7-7906bdc749ae
// d6287f10-3c68-4d0a-a33e-9b4397a90cb7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment