DEV Community

Vineeth.TR
Vineeth.TR

Posted on

Generate dynamic ID's using JavaScript

Create simple ID generator with math random


const generateID = ()=> {
   return Math.random().toString(36).slice(2)
}


// How to use

const UID = generateID() 


Enter fullscreen mode Exit fullscreen mode

Generate dynamic ID's with length control


const generateID = (length)=> {
   const id = Math.random().toString(36).slice(2);
   const uid = [...Array(length)].reduce((r)=> {
           return r+id[~~(Math.random()*id.length)]
   }, '')
}


// How to use

const UID = generateID(8) 


Enter fullscreen mode Exit fullscreen mode

Generate UUID with RFc standard

RFc standard UUIDs must be of the form xxxxxxxx-Mxxx-Nxxx-xxxxxxxxxxxx , where x is one of [0-9, a-f] M is one of [1-5] and N is [8,9,a or b ]


const generateUUID= ()=> {
   const placeholder = [1e7]+-1e3+-4e3+-8e3+-1e11;
   const uid = () => {
     const id = crypto.getRandomValues(new Uint8Array(1));
     return (uid ^ id[0] & 15 >> uid / 4).toString(16)
   }
   return placeholder.replace(/[018]/g, uid)
}


// How to use

const UUID = generateUUID() 


Enter fullscreen mode Exit fullscreen mode

Top comments (0)