How to generate random hex string in javascript

Viewed 29813

How to generate a random string containing only hex characters (0123456789abcdef) of a given length?

11 Answers

Short alternative using spread operator and .map()


Demo 1

const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

console.log(genRanHex(6));
console.log(genRanHex(12));
console.log(genRanHex(3));


  1. Pass in a number (size) for the length of the returned string.

  2. Define an empty array (result) and an array of strings in the range of [0-9] and [a-f] (hexRef).

  3. On each iteration of a for loop, generate a random number 0 to 15 and use it as the index of the value from the array of strings from step 2 (hexRef) -- then push() the value to the empty array from step 2 (result).

  4. Return the array (result) as a join('')ed string.


Demo 2

const getRanHex = size => {
  let result = [];
  let hexRef = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

  for (let n = 0; n < size; n++) {
    result.push(hexRef[Math.floor(Math.random() * 16)]);
  }
  return result.join('');
}

console.log(getRanHex(6));
console.log(getRanHex(12));
console.log(getRanHex(3));

NodeJS Users

You can use randomBytes available in the crypto module, to generate cryptographically strong pseudorandom data of a given size. And you can easily convert it to hex.

import crypto from "crypto";

const randomString = crypto.randomBytes(8).toString("hex");

console.log(randomString)  // ee48d32e6c724c4d

The above code snippet generates a random 8-bytes hex number, you can manipulate the length as you wish.

There are a few ways. One way is to just pull from a predefined string:

function genHexString(len) {
    const hex = '0123456789ABCDEF';
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += hex.charAt(Math.floor(Math.random() * hex.length));
    }
    return output;
}

The other way is to append a random number between 0 and 15 converted to hex with toString:

function genHexString(len) {
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += (Math.floor(Math.random() * 16)).toString(16);
    }
    return output;
}

This securely generates a 32-byte random string and encodes it as hex (64 characters).

Array.from(crypto.getRandomValues(new Uint8Array(32)))
    .map(b => b.toString(16).padStart(2, '0')).join('');

Long version:

function generateRandomHexString(numBytes) {
    const bytes = crypto.getRandomValues(new Uint8Array(numBytes));
    const array = Array.from(bytes);
    const hexPairs = array.map(b => b.toString(16).padStart(2, '0'));
    return hexPairs.join('')
}

If you can use lodash library here is the code snippet to generate a 16 chars string:

let randomString = _.times(16, () => (Math.random()*0xF<<0).toString(16)).join('');

Here's a version that avoids building one digit at a time; it's probably only suitable for short lengths.

function genHexString(len) {
    const str = Math.floor(Math.random() * Math.pow(16, len)).toString(16);
    return "0".repeat(len - str.length) + str;
}

This works for lengths up to 13:

randomHex = length => (
        '0'.repeat(length) 
        + Math.floor((Math.random() * 16 ** length))
        .toString(16)
    ).slice(-length);

console.log(randomHex(4));
console.log(randomHex(6));
console.log(randomHex(13));
console.log(randomHex(20));

Up to 7 characters may be quickly taken from one Math.random() call (A):

const halfBytesIn35 = 7 // = 3.5 bytes
const byte35 = Math.pow(16, halfBytesIn35)
const bytes35 = () => ((Math.random() * byte35) | 0).toString(16).padStart(halfBytesIn35,'0')
console.log('A: ' + bytes35())

const bytes65 = len => Math.floor(Math.random() * Math.pow(16, len*2)).toString(16).padStart(len,'0')
console.log('B: ' + bytes65(6))

function moreBytes (len) {
  len *= 2; // alternative: len <<= 1 if you do not use half bytes. This might allow optimizations based on len always being an Integer then.
  let builder = "";
  while (len > 0) {
    builder += bytes35()
    len -= 7
  }
  return builder.slice(0,len)
}
console.log('C: ' + moreBytes(16))

Store the Math.pow constant if you plan to use this with high frequency.

An 8th letter overflows into the sign bit in the binary floor.

You can reach up to 13 characters from one call by using Math.floor instead (B) or even loop the generator for an arbitrary length (C).

Note that this could be used to define premature optimization. If your bottleneck really is the creation of Random Numbers consider using LUTs. This is common if you are developing for embedded. (And in this case somehow got stuck using javascript, but do not have the timebuget to generate random Numbers)

Using for Loop, charAt and Math.random

let result = "";
let hexChar = "0123456789abcdef";
for (var i = 0; i < 6; i++) {
  result += hexChar.charAt(Math.floor(Math.random() * hexChar.length));
}
console.log(`#${result}`);

Using Math.random, you can do 13 characters at a time in a convenient way. If you want an arbitrary length string, you can still do it with a "one-liner":

const makeRandomHexString = (length: number) =>
  Array.from({ length: Math.ceil(length / 13) })
    .map(() =>
      Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2))
        .toString(16)
        .padStart(13, '0')
    )
    .join('')
    .substring(0, length);

Here is a simplified program to generate random hexadecimal Colour code:

let items = ["a", "b", "c", "d", "e", "f"];
let item = items[Math.floor(Math.random() * items.length)];
console.log(item);

let random = Math.random().toString().slice(2, 6);
console.log(`#${item}${random}${item}`);

Related