How to generate a random string containing only hex characters (0123456789abcdef) of a given length?
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.
Short alternative using spread operator and .map()
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));
Pass in a number (size
) for the length of the returned string.
Define an empty array (result
) and an array of strings in the range of [0-9]
and [a-f]
(hexRef
).
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
).
Return the array (result
) as a join('')
ed string.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With