javascripthex

Javascript generate random hexadecimal


How can I randomly generate a 160 bits (20 bytes) long hexadecimal as a string (same length as Git commit hashes), for use as a unique identifier?


Solution

  • There is cyrpto.getRandomValues in modern browser, support is pretty good. -> https://caniuse.com/#feat=getrandomvalues

    So using this you could do ->

    const a = [...crypto.getRandomValues(new Uint8Array(20))].map(m=>('0'+m.toString(16)).slice(-2)).join('');
    
    console.log(a);