Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random hex string in javascript

Tags:

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

like image 231
Alessandro Dionisi Avatar asked Oct 10 '19 14:10

Alessandro Dionisi


People also ask

How do I print a random string in Javascript?

random() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9). The for loop is used to loop through the number passed into the generateString() function. During each iteration, a random character is generated.


2 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));
like image 75
zer00ne Avatar answered Oct 30 '22 06:10

zer00ne


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.

like image 24
Aminu Kano Avatar answered Oct 30 '22 07:10

Aminu Kano