Cheatsheet collection for go, rust and javascript.

How to generate uuid in JavaScript?



If you are in nodejs don't forget to import this package.

import crypto from 'crypto'

Using crypto this is work on browser and nodejs. This is usefull when you are working with nodejs 19.0 and you want to support old browsers.

function uuid() {
    return ('10000000-1000-4000-8000-100000000000').replace(/[018]/g, c => (
        c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)

Using math random not recomended but ok for small project.

function uuid() {
  const  uuidReplacer = (c) => {
    const r = Math.random()*16|0
    const v = c === 'x' ? r : (r&0x3|0x8)
    return v.toString(16)
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, uuidReplacer)